Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCases.cs @ 6912

Last change on this file since 6912 was 6912, checked in by mkommend, 13 years ago

#1653: Corrected coding conventions unit test.

File size: 45.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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    [TestMethod]
531    public void CodingConventions() {
532      List<string> lowerCaseMethodNames = new List<string>();
533      List<string> lowerCaseProperties = new List<string>();
534      List<string> lowerCaseFields = new List<string>();
535      foreach (Assembly a in PluginLoader.Assemblies) {
536        if (!a.GetName().Name.StartsWith("HeuristicLab"))
537          continue;
538        foreach (Type t in a.GetTypes()) {
539          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
540            if (mi.DeclaringType.Name.StartsWith("<>"))
541              continue;
542            if (char.IsLower(mi.Name[0])) {
543              if (mi.MemberType == MemberTypes.Field)
544                lowerCaseFields.Add(formatFullMemberName(mi));
545              if (mi.MemberType == MemberTypes.Property)
546                lowerCaseProperties.Add(formatFullMemberName(mi));
547              if (mi.MemberType == MemberTypes.Method &&
548                !mi.Name.StartsWith("get_") &&
549                !mi.Name.StartsWith("set_") &&
550                !mi.Name.StartsWith("add_") &&
551                !mi.Name.StartsWith("remove_") &&
552                !mi.Name.StartsWith("op_"))
553                lowerCaseMethodNames.Add(formatFullMemberName(mi));
554            }
555          }
556        }
557      }
558      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
559      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
560      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
561    }
562
563    [TestMethod]
564    public void Number2StringDecomposer() {
565      NumberTest sdt = new NumberTest();
566      XmlGenerator.Serialize(sdt, tempFile,
567        new Configuration(new XmlFormat(),
568          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
569          new List<ICompositeSerializer> {
570            new StorableSerializer(),
571            new Number2StringSerializer() }));
572      object o = XmlParser.Deserialize(tempFile);
573      Assert.AreEqual(
574        DebugStringGenerator.Serialize(sdt),
575        DebugStringGenerator.Serialize(o));
576      Assert.IsTrue(sdt.Equals(o));
577    }
578
579    [TestMethod]
580    public void Enums() {
581      EnumTest et = new EnumTest();
582      et.simpleEnum = SimpleEnum.two;
583      et.complexEnum = ComplexEnum.three;
584      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
585      XmlGenerator.Serialize(et, tempFile);
586      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
587      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
588      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
589      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
590    }
591
592    [TestMethod]
593    public void TestAliasingWithOverriddenEquals() {
594      List<IntWrapper> ints = new List<IntWrapper>();
595      ints.Add(new IntWrapper(1));
596      ints.Add(new IntWrapper(1));
597      Assert.AreEqual(ints[0], ints[1]);
598      Assert.AreNotSame(ints[0], ints[1]);
599      XmlGenerator.Serialize(ints, tempFile);
600      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
601      Assert.AreEqual(newInts[0].Value, 1);
602      Assert.AreEqual(newInts[1].Value, 1);
603      Assert.AreEqual(newInts[0], newInts[1]);
604      Assert.AreNotSame(newInts[0], newInts[1]);
605    }
606
607    [TestMethod]
608    public void NonDefaultConstructorTest() {
609      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
610      try {
611        XmlGenerator.Serialize(c, tempFile);
612        Assert.Fail("Exception not thrown");
613      }
614      catch (PersistenceException) {
615      }
616    }
617
618    [TestMethod]
619    public void TestSavingException() {
620      List<int> list = new List<int> { 1, 2, 3 };
621      XmlGenerator.Serialize(list, tempFile);
622      NonSerializable s = new NonSerializable();
623      try {
624        XmlGenerator.Serialize(s, tempFile);
625        Assert.Fail("Exception expected");
626      }
627      catch (PersistenceException) { }
628      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
629      Assert.AreEqual(list[0], newList[0]);
630      Assert.AreEqual(list[1], newList[1]);
631    }
632
633    [TestMethod]
634    public void TestTypeStringConversion() {
635      string name = typeof(List<int>[]).AssemblyQualifiedName;
636      string shortName =
637        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
638      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
639      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
640      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
641    }
642
643    [TestMethod]
644    public void TestHexadecimalPublicKeyToken() {
645      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
646      string shortName = "TestClass, TestAssembly";
647      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
648      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
649    }
650
651    [TestMethod]
652    public void TestMultipleFailure() {
653      List<NonSerializable> l = new List<NonSerializable>();
654      l.Add(new NonSerializable());
655      l.Add(new NonSerializable());
656      l.Add(new NonSerializable());
657      try {
658        Serializer s = new Serializer(l,
659          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
660          "ROOT", true);
661        StringBuilder tokens = new StringBuilder();
662        foreach (var token in s) {
663          tokens.Append(token.ToString());
664        }
665        Assert.Fail("Exception expected");
666      }
667      catch (PersistenceException px) {
668        Assert.AreEqual(3, px.Data.Count);
669      }
670    }
671
672    [TestMethod]
673    public void TestAssemblyVersionCheck() {
674      IntWrapper i = new IntWrapper(1);
675      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
676      XmlGenerator g = new XmlGenerator();
677      StringBuilder dataString = new StringBuilder();
678      foreach (var token in s) {
679        dataString.Append(g.Format(token));
680      }
681      StringBuilder typeString = new StringBuilder();
682      foreach (var line in g.Format(s.TypeCache))
683        typeString.Append(line);
684      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
685      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
686      IntWrapper newI = (IntWrapper)d.Deserialize(p);
687      Assert.AreEqual(i.Value, newI.Value);
688
689      string newTypeString = Regex.Replace(typeString.ToString(),
690        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
691        "Version=0.0.9999.9999");
692      try {
693        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
694        Assert.Fail("Exception expected");
695      }
696      catch (PersistenceException x) {
697        Assert.IsTrue(x.Message.Contains("incompatible"));
698      }
699      newTypeString = Regex.Replace(typeString.ToString(),
700        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
701        "Version=$1.9999.9999");
702      try {
703        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
704        Assert.Fail("Exception expected");
705      }
706      catch (PersistenceException x) {
707        Assert.IsTrue(x.Message.Contains("newer"));
708      }
709    }
710
711    [TestMethod]
712    public void InheritanceTest() {
713      New n = new New();
714      XmlGenerator.Serialize(n, tempFile);
715      New nn = (New)XmlParser.Deserialize(tempFile);
716      Assert.AreEqual(n.Name, nn.Name);
717      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
718    }
719
720    [StorableClass]
721    class Child {
722      [Storable]
723      public GrandParent grandParent;
724    }
725
726    [StorableClass]
727    class Parent {
728      [Storable]
729      public Child child;
730    }
731
732    [StorableClass]
733    class GrandParent {
734      [Storable]
735      public Parent parent;
736    }
737
738    [TestMethod]
739    public void InstantiateParentChainReference() {
740      GrandParent gp = new GrandParent();
741      gp.parent = new Parent();
742      gp.parent.child = new Child();
743      gp.parent.child.grandParent = gp;
744      Assert.AreSame(gp, gp.parent.child.grandParent);
745      XmlGenerator.Serialize(gp, tempFile);
746      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
747      Assert.AreSame(newGp, newGp.parent.child.grandParent);
748    }
749
750    struct TestStruct {
751      int value;
752      int PropertyValue { get; set; }
753      public TestStruct(int value)
754        : this() {
755        this.value = value;
756        PropertyValue = value;
757      }
758    }
759
760    [TestMethod]
761    public void StructTest() {
762      TestStruct s = new TestStruct(10);
763      XmlGenerator.Serialize(s, tempFile);
764      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
765      Assert.AreEqual(s, newS);
766    }
767
768    [TestMethod]
769    public void PointTest() {
770      Point p = new Point(12, 34);
771      XmlGenerator.Serialize(p, tempFile);
772      Point newP = (Point)XmlParser.Deserialize(tempFile);
773      Assert.AreEqual(p, newP);
774    }
775
776    [TestMethod]
777    public void NullableValueTypes() {
778      double?[] d = new double?[] { null, 1, 2, 3 };
779      XmlGenerator.Serialize(d, tempFile);
780      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
781      Assert.AreEqual(d[0], newD[0]);
782      Assert.AreEqual(d[1], newD[1]);
783      Assert.AreEqual(d[2], newD[2]);
784      Assert.AreEqual(d[3], newD[3]);
785    }
786
787    [TestMethod]
788    public void BitmapTest() {
789      Icon icon = System.Drawing.SystemIcons.Hand;
790      Bitmap bitmap = icon.ToBitmap();
791      XmlGenerator.Serialize(bitmap, tempFile);
792      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
793
794      Assert.AreEqual(bitmap.Size, newBitmap.Size);
795      for (int i = 0; i < bitmap.Size.Width; i++)
796        for (int j = 0; j < bitmap.Size.Height; j++)
797          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
798    }
799
800    [StorableClass]
801    private class PersistenceHooks {
802      [Storable]
803      public int a;
804      [Storable]
805      public int b;
806      public int sum;
807      public bool WasSerialized { get; private set; }
808      [StorableHook(HookType.BeforeSerialization)]
809      void PreSerializationHook() {
810        WasSerialized = true;
811      }
812      [StorableHook(HookType.AfterDeserialization)]
813      void PostDeserializationHook() {
814        sum = a + b;
815      }
816    }
817
818    [TestMethod]
819    public void HookTest() {
820      PersistenceHooks hookTest = new PersistenceHooks();
821      hookTest.a = 2;
822      hookTest.b = 5;
823      Assert.IsFalse(hookTest.WasSerialized);
824      Assert.AreEqual(hookTest.sum, 0);
825      XmlGenerator.Serialize(hookTest, tempFile);
826      Assert.IsTrue(hookTest.WasSerialized);
827      Assert.AreEqual(hookTest.sum, 0);
828      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
829      Assert.AreEqual(newHookTest.a, hookTest.a);
830      Assert.AreEqual(newHookTest.b, hookTest.b);
831      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
832      Assert.IsFalse(newHookTest.WasSerialized);
833    }
834
835    [StorableClass]
836    private class CustomConstructor {
837      public string Value = "none";
838      public CustomConstructor() {
839        Value = "default";
840      }
841      [StorableConstructor]
842      private CustomConstructor(bool deserializing) {
843        Assert.IsTrue(deserializing);
844        Value = "persistence";
845      }
846    }
847
848    [TestMethod]
849    public void TestCustomConstructor() {
850      CustomConstructor cc = new CustomConstructor();
851      Assert.AreEqual(cc.Value, "default");
852      XmlGenerator.Serialize(cc, tempFile);
853      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
854      Assert.AreEqual(newCC.Value, "persistence");
855    }
856
857    [StorableClass]
858    public class ExplodingDefaultConstructor {
859      public ExplodingDefaultConstructor() {
860        throw new Exception("this constructor will always fail");
861      }
862      public ExplodingDefaultConstructor(string password) {
863      }
864    }
865
866    [TestMethod]
867    public void TestConstructorExceptionUnwrapping() {
868      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
869      XmlGenerator.Serialize(x, tempFile);
870      try {
871        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
872        Assert.Fail("Exception expected");
873      }
874      catch (PersistenceException pe) {
875        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
876      }
877    }
878
879    [TestMethod]
880    public void TestRejectionJustifications() {
881      NonSerializable ns = new NonSerializable();
882      try {
883        XmlGenerator.Serialize(ns, tempFile);
884        Assert.Fail("PersistenceException expected");
885      }
886      catch (PersistenceException x) {
887        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
888      }
889    }
890
891    [TestMethod]
892    public void TestStreaming() {
893      using (MemoryStream stream = new MemoryStream()) {
894        Root r = InitializeComplexStorable();
895        XmlGenerator.Serialize(r, stream);
896        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
897          Root newR = (Root)XmlParser.Deserialize(stream2);
898          CompareComplexStorables(r, newR);
899        }
900      }
901    }
902
903    [StorableClass]
904    public class HookInheritanceTestBase {
905      [Storable]
906      public object a;
907      public object link;
908      [StorableHook(HookType.AfterDeserialization)]
909      private void relink() {
910        link = a;
911      }
912    }
913
914    [StorableClass]
915    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
916      [Storable]
917      public object b;
918      [StorableHook(HookType.AfterDeserialization)]
919      private void relink() {
920        Assert.AreSame(a, link);
921        link = b;
922      }
923    }
924
925    [TestMethod]
926    public void TestLinkInheritance() {
927      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
928      c.a = new object();
929      XmlGenerator.Serialize(c, tempFile);
930      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
931      Assert.AreSame(c.b, c.link);
932    }
933
934    [StorableClass(StorableClassType.AllFields)]
935    public class AllFieldsStorable {
936      public int Value1 = 1;
937      [Storable]
938      public int Value2 = 2;
939      public int Value3 { get; private set; }
940      public int Value4 { get; private set; }
941      [StorableConstructor]
942      public AllFieldsStorable(bool isDeserializing) {
943        if (!isDeserializing) {
944          Value1 = 12;
945          Value2 = 23;
946          Value3 = 34;
947          Value4 = 56;
948        }
949      }
950    }
951
952    [TestMethod]
953    public void TestStorableClassDiscoveryAllFields() {
954      AllFieldsStorable afs = new AllFieldsStorable(false);
955      XmlGenerator.Serialize(afs, tempFile);
956      AllFieldsStorable newAfs = (AllFieldsStorable)XmlParser.Deserialize(tempFile);
957      Assert.AreEqual(afs.Value1, newAfs.Value1);
958      Assert.AreEqual(afs.Value2, newAfs.Value2);
959      Assert.AreEqual(0, newAfs.Value3);
960      Assert.AreEqual(0, newAfs.Value4);
961    }
962
963    [StorableClass(StorableClassType.AllProperties)]
964    public class AllPropertiesStorable {
965      public int Value1 = 1;
966      [Storable]
967      public int Value2 = 2;
968      public int Value3 { get; private set; }
969      public int Value4 { get; private set; }
970      [StorableConstructor]
971      public AllPropertiesStorable(bool isDeserializing) {
972        if (!isDeserializing) {
973          Value1 = 12;
974          Value2 = 23;
975          Value3 = 34;
976          Value4 = 56;
977        }
978      }
979    }
980
981    [TestMethod]
982    public void TestStorableClassDiscoveryAllProperties() {
983      AllPropertiesStorable afs = new AllPropertiesStorable(false);
984      XmlGenerator.Serialize(afs, tempFile);
985      AllPropertiesStorable newAfs = (AllPropertiesStorable)XmlParser.Deserialize(tempFile);
986      Assert.AreEqual(1, newAfs.Value1);
987      Assert.AreEqual(2, newAfs.Value2);
988      Assert.AreEqual(afs.Value3, newAfs.Value3);
989      Assert.AreEqual(afs.Value4, newAfs.Value4);
990
991    }
992
993    [StorableClass(StorableClassType.AllFieldsAndAllProperties)]
994    public class AllFieldsAndAllPropertiesStorable {
995      public int Value1 = 1;
996      [Storable]
997      public int Value2 = 2;
998      public int Value3 { get; private set; }
999      public int Value4 { get; private set; }
1000      [StorableConstructor]
1001      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1002        if (!isDeserializing) {
1003          Value1 = 12;
1004          Value2 = 23;
1005          Value3 = 34;
1006          Value4 = 56;
1007        }
1008      }
1009    }
1010
1011    [TestMethod]
1012    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1013      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1014      XmlGenerator.Serialize(afs, tempFile);
1015      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)XmlParser.Deserialize(tempFile);
1016      Assert.AreEqual(afs.Value1, newAfs.Value1);
1017      Assert.AreEqual(afs.Value2, newAfs.Value2);
1018      Assert.AreEqual(afs.Value3, newAfs.Value3);
1019      Assert.AreEqual(afs.Value4, newAfs.Value4);
1020    }
1021
1022    [StorableClass(StorableClassType.MarkedOnly)]
1023    public class MarkedOnlyStorable {
1024      public int Value1 = 1;
1025      [Storable]
1026      public int Value2 = 2;
1027      public int Value3 { get; private set; }
1028      public int Value4 { get; private set; }
1029      [StorableConstructor]
1030      public MarkedOnlyStorable(bool isDeserializing) {
1031        if (!isDeserializing) {
1032          Value1 = 12;
1033          Value2 = 23;
1034          Value3 = 34;
1035          Value4 = 56;
1036        }
1037      }
1038    }
1039
1040    [TestMethod]
1041    public void TestStorableClassDiscoveryMarkedOnly() {
1042      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1043      XmlGenerator.Serialize(afs, tempFile);
1044      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
1045      Assert.AreEqual(1, newAfs.Value1);
1046      Assert.AreEqual(afs.Value2, newAfs.Value2);
1047      Assert.AreEqual(0, newAfs.Value3);
1048      Assert.AreEqual(0, newAfs.Value4);
1049    }
1050
1051    [TestMethod]
1052    public void TestLineEndings() {
1053      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1054      List<string> lines = new List<string>();
1055      foreach (var br in lineBreaks)
1056        lines.Add("line1" + br + "line2");
1057      XmlGenerator.Serialize(lines, tempFile);
1058      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
1059      Assert.AreEqual(lines.Count, newLines.Count);
1060      for (int i = 0; i < lineBreaks.Count; i++) {
1061        Assert.AreEqual(lines[i], newLines[i]);
1062      }
1063    }
1064
1065    [TestMethod]
1066    public void TestSpecialNumbers() {
1067      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1068      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1069      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1070      Assert.IsTrue(double.IsNaN(specials[2]));
1071      XmlGenerator.Serialize(specials, tempFile);
1072      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
1073      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1074      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1075      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1076    }
1077
1078    [TestMethod]
1079    public void TestStringSplit() {
1080      string s = "1.2;2.3;3.4;;;4.9";
1081      var l = s.EnumerateSplit(';').ToList();
1082      Assert.AreEqual("1.2", l[0]);
1083      Assert.AreEqual("2.3", l[1]);
1084      Assert.AreEqual("3.4", l[2]);
1085      Assert.AreEqual("4.9", l[3]);
1086    }
1087
1088    [TestMethod]
1089    public void TestCompactNumberArraySerializer() {
1090      System.Random r = new System.Random();
1091      double[] a = new double[CompactNumberArray2StringSerializer.SPLIT_THRESHOLD * 2 + 1];
1092      for (int i = 0; i < a.Length; i++)
1093        a[i] = r.Next(10);
1094      var config = ConfigurationService.Instance.GetDefaultConfig(new XmlFormat());
1095      config = new Configuration(config.Format,
1096        config.PrimitiveSerializers.Where(s => s.SourceType != typeof(double[])),
1097        config.CompositeSerializers);
1098      XmlGenerator.Serialize(a, tempFile, config);
1099      double[] newA = XmlParser.Deserialize<double[]>(tempFile);
1100      Assert.AreEqual(a.Length, newA.Length);
1101      for (int i = 0; i < a.Rank; i++) {
1102        Assert.AreEqual(a.GetLength(i), newA.GetLength(i));
1103        Assert.AreEqual(a.GetLowerBound(i), newA.GetLowerBound(i));
1104      }
1105      for (int i = 0; i < a.Length; i++) {
1106        Assert.AreEqual(a[i], newA[i]);
1107      }
1108    }
1109    private class IdentityComparer<T> : IEqualityComparer<T> {
1110
1111      public bool Equals(T x, T y) {
1112        return x.Equals(y);
1113      }
1114
1115      public int GetHashCode(T obj) {
1116        return obj.GetHashCode();
1117      }
1118    }
1119
1120    [TestMethod]
1121    public void TestHashSetSerializer() {
1122      var hashSets = new List<HashSet<int>>() {
1123        new HashSet<int>(new[] { 1, 2, 3 }),
1124        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1125      };
1126      XmlGenerator.Serialize(hashSets, tempFile);
1127      var newHashSets = XmlParser.Deserialize<List<HashSet<int>>>(tempFile);
1128      Assert.IsTrue(newHashSets[0].Contains(1));
1129      Assert.IsTrue(newHashSets[0].Contains(2));
1130      Assert.IsTrue(newHashSets[0].Contains(3));
1131      Assert.IsTrue(newHashSets[1].Contains(4));
1132      Assert.IsTrue(newHashSets[1].Contains(5));
1133      Assert.IsTrue(newHashSets[1].Contains(6));
1134      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1135      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1136    }
1137
1138    [TestMethod]
1139    public void TestConcreteDictionarySerializer() {
1140      var dictionaries = new List<Dictionary<int, int>>() {
1141        new Dictionary<int, int>(),
1142        new Dictionary<int, int>(new IdentityComparer<int>()),
1143      };
1144      dictionaries[0].Add(1, 1);
1145      dictionaries[0].Add(2, 2);
1146      dictionaries[0].Add(3, 3);
1147      dictionaries[1].Add(4, 4);
1148      dictionaries[1].Add(5, 5);
1149      dictionaries[1].Add(6, 6);
1150      XmlGenerator.Serialize(dictionaries, tempFile, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1151      var newDictionaries = XmlParser.Deserialize<List<Dictionary<int, int>>>(tempFile);
1152      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1153      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1154      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1155      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1156      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1157      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1158      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1159      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1160      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1161      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1162      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1163      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1164      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1165      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1166    }
1167
1168    [StorableClass]
1169    public class ReadOnlyFail {
1170      [Storable]
1171      public string ReadOnly {
1172        get { return "fail"; }
1173      }
1174    }
1175
1176    [TestMethod]
1177    public void TestReadOnlyFail() {
1178      try {
1179        XmlGenerator.Serialize(new ReadOnlyFail(), tempFile);
1180        Assert.Fail("Exception expected");
1181      }
1182      catch (PersistenceException) {
1183      }
1184      catch {
1185        Assert.Fail("PersistenceException expected");
1186      }
1187    }
1188
1189
1190    [StorableClass]
1191    public class WriteOnlyFail {
1192      [Storable]
1193      public string WriteOnly {
1194        set { throw new InvalidOperationException("this property should never be set."); }
1195      }
1196    }
1197
1198    [TestMethod]
1199    public void TestWriteOnlyFail() {
1200      try {
1201        XmlGenerator.Serialize(new WriteOnlyFail(), tempFile);
1202        Assert.Fail("Exception expected");
1203      }
1204      catch (PersistenceException) {
1205      }
1206      catch {
1207        Assert.Fail("PersistenceException expected.");
1208      }
1209    }
1210
1211    [StorableClass]
1212    public class OneWayTest {
1213      public OneWayTest() { this.value = "default"; }
1214      public string value;
1215      [Storable(AllowOneWay = true)]
1216      public string ReadOnly {
1217        get { return "ReadOnly"; }
1218      }
1219      [Storable(AllowOneWay = true)]
1220      public string WriteOnly {
1221        set { this.value = value; }
1222      }
1223    }
1224
1225    [TestMethod]
1226    public void TestOneWaySerialization() {
1227      var test = new OneWayTest();
1228      var serializer = new Serializer(test, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1229      var it = serializer.GetEnumerator();
1230      it.MoveNext();
1231      Assert.AreEqual("ROOT", ((BeginToken)it.Current).Name); it.MoveNext();
1232      Assert.AreEqual("ReadOnly", ((PrimitiveToken)it.Current).Name); it.MoveNext();
1233      Assert.AreEqual("ROOT", ((EndToken)it.Current).Name); it.MoveNext();
1234      var deserializer = new Deserializer(new[] {
1235        new TypeMapping(0, typeof(OneWayTest).AssemblyQualifiedName, typeof(StorableSerializer).AssemblyQualifiedName),
1236        new TypeMapping(1, typeof(string).AssemblyQualifiedName, typeof(String2XmlSerializer).AssemblyQualifiedName) });
1237      var newTest = (OneWayTest)deserializer.Deserialize(new ISerializationToken[] {
1238        new BeginToken("ROOT", 0, 0),
1239        new PrimitiveToken("WriteOnly", 1, 1, new XmlString("<![CDATA[serial data]]>")),
1240        new EndToken("ROOT", 0, 0)
1241      });
1242      Assert.AreEqual("serial data", newTest.value);
1243    }
1244
1245    [TestMethod]
1246    public void TestTypeCacheExport() {
1247      var test = new List<List<int>>();
1248      test.Add(new List<int>() { 1, 2, 3 });
1249      IEnumerable<Type> types;
1250      using (var stream = new MemoryStream()) {
1251        XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1252      }
1253      List<Type> t = new List<Type>(types);
1254      // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1255      Assert.IsTrue(t.Contains(typeof(List<int>)));
1256      Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1257      Assert.AreEqual(t.Count, 2);
1258    }
1259
1260    [TestMethod]
1261    public void TupleTest() {
1262      var t1 = Tuple.Create(1);
1263      var t2 = Tuple.Create('1', "2");
1264      var t3 = Tuple.Create(3.0, 3f, 5);
1265      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1266      var tuple = Tuple.Create(t1, t2, t3, t4);
1267      XmlGenerator.Serialize(tuple, tempFile);
1268      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);
1269      Assert.AreEqual(tuple, newTuple);
1270    }
1271
1272    [TestMethod]
1273    public void FontTest() {
1274      List<Font> fonts = new List<Font>() {
1275        new Font(FontFamily.GenericSansSerif, 12),
1276        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1277        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1278        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1279      };
1280      XmlGenerator.Serialize(fonts, tempFile);
1281      var newFonts = XmlParser.Deserialize<List<Font>>(tempFile);
1282      Assert.AreEqual(fonts[0], newFonts[0]);
1283      Assert.AreEqual(fonts[1], newFonts[1]);
1284      Assert.AreEqual(fonts[2], newFonts[2]);
1285      Assert.AreEqual(fonts[3], newFonts[3]);
1286    }
1287
1288    [TestMethod]
1289    public void ConcurrencyTest() {
1290      int n = 20;
1291      Task[] tasks = new Task[n];
1292      for (int i = 0; i < n; i++) {
1293        tasks[i] = Task.Factory.StartNew((idx) => {
1294          byte[] data;
1295          using (var stream = new MemoryStream()) {
1296            XmlGenerator.Serialize(new GeneticAlgorithm(), stream);
1297            data = stream.ToArray();
1298          }
1299        }, i);
1300      }
1301      Task.WaitAll(tasks);
1302    }
1303
1304    [TestMethod]
1305    public void ConcurrentBitmapTest() {
1306      Bitmap b = new Bitmap(300, 300);
1307      System.Random r = new System.Random();
1308      for (int x = 0; x < b.Height; x++) {
1309        for (int y = 0; y < b.Width; y++) {
1310          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1311        }
1312      }
1313      Task[] tasks = new Task[20];
1314      byte[][] datas = new byte[tasks.Length][];
1315      for (int i = 0; i < tasks.Length; i++) {
1316        tasks[i] = Task.Factory.StartNew((idx) => {
1317          using (var stream = new MemoryStream()) {
1318            XmlGenerator.Serialize(b, stream);
1319            datas[(int)idx] = stream.ToArray();
1320          }
1321        }, i);
1322      }
1323      Task.WaitAll(tasks);
1324    }
1325
1326    [ClassInitialize]
1327    public static void Initialize(TestContext testContext) {
1328      ConfigurationService.Instance.Reset();
1329    }
1330  }
1331}
Note: See TracBrowser for help on using the repository browser.