Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6653 was 6446, checked in by epitzer, 13 years ago

Lock bitmap while saving and remove configuration info when other exceptions occur (#1560)

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