Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.0/HeuristicLab.Persistence/3.3/Tests/UseCases.cs @ 14538

Last change on this file since 14538 was 3811, checked in by epitzer, 14 years ago

correct and speed-up serialization for number enumerables (#548)

File size: 35.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Text;
24using System.Collections.Generic;
25using System.Linq;
26using Microsoft.VisualStudio.TestTools.UnitTesting;
27using HeuristicLab.Persistence.Core;
28using System.Collections;
29using HeuristicLab.Persistence.Default.Xml;
30using HeuristicLab.Persistence.Default.DebugString;
31using System.IO;
32using System.Reflection;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Persistence.Interfaces;
35using HeuristicLab.Persistence.Default.Xml.Primitive;
36using HeuristicLab.Persistence.Default.CompositeSerializers;
37using HeuristicLab.Persistence.Auxiliary;
38using System.Text.RegularExpressions;
39using System.Drawing;
40using System.Drawing.Imaging;
41
42namespace HeuristicLab.Persistence_33.Tests {
43
44  [StorableClass] 
45  public class NumberTest {
46    [Storable]
47    private bool _bool = true;
48    [Storable]
49    private byte _byte = 0xFF;
50    [Storable]
51    private sbyte _sbyte = 0xF;
52    [Storable]
53    private short _short = -123;
54    [Storable]
55    private ushort _ushort = 123;
56    [Storable]
57    private int _int = -123;
58    [Storable]
59    private uint _uint = 123;
60    [Storable]
61    private long _long = 123456;
62    [Storable]
63    private ulong _ulong = 123456;
64    public override bool Equals(object obj) {
65      NumberTest nt = obj as NumberTest;
66      if (nt == null)
67        throw new NotSupportedException();
68      return
69        nt._bool == _bool &&
70        nt._byte == _byte &&
71        nt._sbyte == _sbyte &&
72        nt._short == _short &&
73        nt._ushort == _ushort &&
74        nt._int == _int &&
75        nt._uint == _uint &&
76        nt._long == _long &&
77        nt._ulong == _ulong;
78    }
79    public override int GetHashCode() {
80      return
81        _bool.GetHashCode() ^
82        _byte.GetHashCode() ^
83        _sbyte.GetHashCode() ^
84        _short.GetHashCode() ^
85        _short.GetHashCode() ^
86        _int.GetHashCode() ^
87        _uint.GetHashCode() ^
88        _long.GetHashCode() ^
89        _ulong.GetHashCode();
90    }
91  }
92
93  [StorableClass]
94  public class NonDefaultConstructorClass {
95    [Storable]
96    int value;
97    public NonDefaultConstructorClass(int value) {
98      this.value = value;
99    }
100  }
101
102  [StorableClass]
103  public class IntWrapper {
104
105    [Storable]
106    public int Value;
107
108    private IntWrapper() { }
109
110    public IntWrapper(int value) {
111      this.Value = value;
112    }
113
114    public override bool Equals(object obj) {
115      if (obj as IntWrapper == null)
116        return false;
117      return Value.Equals(((IntWrapper)obj).Value);
118    }
119    public override int GetHashCode() {
120      return Value.GetHashCode();
121    }
122
123  }
124
125  [StorableClass]
126  public class PrimitivesTest : NumberTest {
127    [Storable]
128    private char c = 'e';
129    [Storable]
130    private long[,] _long_array =
131      new long[,] { { 123, 456, }, { 789, 123 } };
132    [Storable]
133    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
134    [Storable]
135    private object o = new object();
136    public override bool Equals(object obj) {
137      PrimitivesTest pt = obj as PrimitivesTest;
138      if (pt == null)
139        throw new NotSupportedException();
140      return base.Equals(obj) &&
141        c == pt.c &&
142        _long_array == pt._long_array &&
143        list == pt.list &&
144        o == pt.o;
145    }
146    public override int GetHashCode() {
147      return base.GetHashCode() ^
148        c.GetHashCode() ^
149        _long_array.GetHashCode() ^
150        list.GetHashCode() ^
151        o.GetHashCode();
152    }
153  }
154
155  public enum TestEnum { va1, va2, va3, va8 } ;
156
157  [StorableClass]
158  public class RootBase {
159    [Storable]
160    private string baseString = "   Serial  ";
161    [Storable]
162    public TestEnum myEnum = TestEnum.va3;
163    public override bool Equals(object obj) {
164      RootBase rb = obj as RootBase;
165      if (rb == null)
166        throw new NotSupportedException();
167      return baseString == rb.baseString &&
168        myEnum == rb.myEnum;
169    }
170    public override int GetHashCode() {
171      return baseString.GetHashCode() ^
172        myEnum.GetHashCode();
173    }
174  }
175
176  [StorableClass]
177  public class Root : RootBase {
178    [Storable]
179    public Stack<int> intStack = new Stack<int>();
180    [Storable]
181    public int[] i = new[] { 3, 4, 5, 6 };
182    [Storable(Name = "Test String")]
183    public string s;
184    [Storable]
185    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
186    [Storable]
187    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
188    [Storable]
189    public Custom c;
190    [Storable]
191    public List<Root> selfReferences;
192    [Storable]
193    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
194    [Storable]
195    public bool boolean = true;
196    [Storable]
197    public DateTime dateTime;
198    [Storable]
199    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
200    [Storable]
201    public Dictionary<string, int> dict = new Dictionary<string, int>();
202    [Storable(DefaultValue = "default")]
203    public string uninitialized;
204  }
205
206  public enum SimpleEnum { one, two, three }
207  public enum ComplexEnum { one = 1, two = 2, three = 3 }
208  [FlagsAttribute]
209  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
210
211  [StorableClass]
212  public class EnumTest {
213    [Storable]
214    public SimpleEnum simpleEnum = SimpleEnum.one;
215    [Storable]
216    public ComplexEnum complexEnum = (ComplexEnum)2;
217    [Storable]
218    public TrickyEnum trickyEnum = (TrickyEnum)15;
219  }
220
221  [StorableClass]
222  public class Custom {
223    [Storable]
224    public int i;
225    [Storable]
226    public Root r;
227    [Storable]
228    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
229  }
230
231  [StorableClass]
232  public class Manager {
233
234    public DateTime lastLoadTime;
235    [Storable]
236    private DateTime lastLoadTimePersistence {
237      get { return lastLoadTime; }
238      set { lastLoadTime = DateTime.Now; }
239    }
240    [Storable]
241    public double? dbl;
242  }
243
244  [StorableClass]
245  public class C {
246    [Storable]
247    public C[][] allCs;
248    [Storable]
249    public KeyValuePair<List<C>, C> kvpList;
250  }
251
252  public class NonSerializable {
253    int x = 0;
254    public override bool Equals(object obj) {
255      NonSerializable ns = obj as NonSerializable;
256      if (ns == null)
257        throw new NotSupportedException();
258      return ns.x == x;
259    }
260    public override int GetHashCode() {
261      return x.GetHashCode();
262    }
263  }
264
265
266  [TestClass]
267  public class UseCases {
268
269    private string tempFile;
270
271    [TestInitialize()]
272    public void CreateTempFile() {
273      tempFile = Path.GetTempFileName();
274    }
275
276    [TestCleanup()]
277    public void ClearTempFile() {
278      StreamReader reader = new StreamReader(tempFile);
279      string s = reader.ReadToEnd();
280      reader.Close();
281      File.Delete(tempFile);
282    }
283
284    [TestMethod]
285    public void ComplexStorable() {
286      Root r = InitializeComplexStorable();
287      XmlGenerator.Serialize(r, tempFile);
288      Root newR = (Root)XmlParser.Deserialize(tempFile);
289      CompareComplexStorables(r, newR);
290    }
291
292    private static void CompareComplexStorables(Root r, Root newR) {
293      Assert.AreEqual(
294        DebugStringGenerator.Serialize(r),
295        DebugStringGenerator.Serialize(newR));
296      Assert.AreSame(newR, newR.selfReferences[0]);
297      Assert.AreNotSame(r, newR);
298      Assert.AreEqual(r.myEnum, TestEnum.va1);
299      Assert.AreEqual(r.i[0], 7);
300      Assert.AreEqual(r.i[1], 5);
301      Assert.AreEqual(r.i[2], 6);
302      Assert.AreEqual(r.s, "new value");
303      Assert.AreEqual(r.intArray[0], 3);
304      Assert.AreEqual(r.intArray[1], 2);
305      Assert.AreEqual(r.intArray[2], 1);
306      Assert.AreEqual(r.intList[0], 9);
307      Assert.AreEqual(r.intList[1], 8);
308      Assert.AreEqual(r.intList[2], 7);
309      Assert.AreEqual(r.multiDimArray[0, 0], 5);
310      Assert.AreEqual(r.multiDimArray[0, 1], 4);
311      Assert.AreEqual(r.multiDimArray[0, 2], 3);
312      Assert.AreEqual(r.multiDimArray[1, 0], 1);
313      Assert.AreEqual(r.multiDimArray[1, 1], 4);
314      Assert.AreEqual(r.multiDimArray[1, 2], 6);
315      Assert.IsFalse(r.boolean);
316      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
317      Assert.AreEqual(r.kvp.Key, "string key");
318      Assert.AreEqual(r.kvp.Value, 321);
319      Assert.IsNull(r.uninitialized);
320      Assert.AreEqual(newR.myEnum, TestEnum.va1);
321      Assert.AreEqual(newR.i[0], 7);
322      Assert.AreEqual(newR.i[1], 5);
323      Assert.AreEqual(newR.i[2], 6);
324      Assert.AreEqual(newR.s, "new value");
325      Assert.AreEqual(newR.intArray[0], 3);
326      Assert.AreEqual(newR.intArray[1], 2);
327      Assert.AreEqual(newR.intArray[2], 1);
328      Assert.AreEqual(newR.intList[0], 9);
329      Assert.AreEqual(newR.intList[1], 8);
330      Assert.AreEqual(newR.intList[2], 7);
331      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
332      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
333      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
334      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
335      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
336      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
337      Assert.AreEqual(newR.intStack.Pop(), 3);
338      Assert.AreEqual(newR.intStack.Pop(), 2);
339      Assert.AreEqual(newR.intStack.Pop(), 1);
340      Assert.IsFalse(newR.boolean);
341      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
342      Assert.AreEqual(newR.kvp.Key, "string key");
343      Assert.AreEqual(newR.kvp.Value, 321);
344      Assert.IsNull(newR.uninitialized);
345    }
346
347    private static Root InitializeComplexStorable() {
348      Root r = new Root();
349      r.intStack.Push(1);
350      r.intStack.Push(2);
351      r.intStack.Push(3);
352      r.selfReferences = new List<Root> { r, r };
353      r.c = new Custom { r = r };
354      r.dict.Add("one", 1);
355      r.dict.Add("two", 2);
356      r.dict.Add("three", 3);
357      r.myEnum = TestEnum.va1;
358      r.i = new[] { 7, 5, 6 };
359      r.s = "new value";
360      r.intArray = new ArrayList { 3, 2, 1 };
361      r.intList = new List<int> { 9, 8, 7 };
362      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
363      r.boolean = false;
364      r.dateTime = DateTime.Now;
365      r.kvp = new KeyValuePair<string, int>("string key", 321);
366      r.uninitialized = null;
367
368      return r;
369    }
370
371    [TestMethod]
372    public void SelfReferences() {
373      C c = new C();
374      C[][] cs = new C[2][];
375      cs[0] = new C[] { c };
376      cs[1] = new C[] { c };
377      c.allCs = cs;
378      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
379      XmlGenerator.Serialize(cs, tempFile);
380      object o = XmlParser.Deserialize(tempFile);
381      Assert.AreEqual(
382        DebugStringGenerator.Serialize(cs),
383        DebugStringGenerator.Serialize(o));
384      Assert.AreSame(c, c.allCs[0][0]);
385      Assert.AreSame(c, c.allCs[1][0]);
386      Assert.AreSame(c, c.kvpList.Key[0]);
387      Assert.AreSame(c, c.kvpList.Value);
388      C[][] newCs = (C[][])o;
389      C newC = newCs[0][0];
390      Assert.AreSame(newC, newC.allCs[0][0]);
391      Assert.AreSame(newC, newC.allCs[1][0]);
392      Assert.AreSame(newC, newC.kvpList.Key[0]);
393      Assert.AreSame(newC, newC.kvpList.Value);
394    }
395
396    [TestMethod]
397    public void ArrayCreation() {
398      ArrayList[] arrayListArray = new ArrayList[4];
399      arrayListArray[0] = new ArrayList();
400      arrayListArray[0].Add(arrayListArray);
401      arrayListArray[0].Add(arrayListArray);
402      arrayListArray[1] = new ArrayList();
403      arrayListArray[1].Add(arrayListArray);
404      arrayListArray[2] = new ArrayList();
405      arrayListArray[2].Add(arrayListArray);
406      arrayListArray[2].Add(arrayListArray);
407      Array a = Array.CreateInstance(
408                              typeof(object),
409                              new[] { 1, 2 }, new[] { 3, 4 });
410      arrayListArray[2].Add(a);
411      XmlGenerator.Serialize(arrayListArray, tempFile);
412      object o = XmlParser.Deserialize(tempFile);
413      Assert.AreEqual(
414        DebugStringGenerator.Serialize(arrayListArray),
415        DebugStringGenerator.Serialize(o));
416      ArrayList[] newArray = (ArrayList[])o;
417      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
418      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
419      Assert.AreSame(newArray, newArray[0][0]);
420      Assert.AreSame(newArray, newArray[2][1]);
421    }
422
423    [TestMethod]
424    public void CustomSerializationProperty() {
425      Manager m = new Manager();
426      XmlGenerator.Serialize(m, tempFile);
427      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
428      Assert.AreNotEqual(
429        DebugStringGenerator.Serialize(m),
430        DebugStringGenerator.Serialize(newM));
431      Assert.AreEqual(m.dbl, newM.dbl);
432      Assert.AreEqual(m.lastLoadTime, new DateTime());
433      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
434      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
435    }
436
437    [TestMethod]
438    public void Primitives() {
439      PrimitivesTest sdt = new PrimitivesTest();
440      XmlGenerator.Serialize(sdt, tempFile);
441      object o = XmlParser.Deserialize(tempFile);
442      Assert.AreEqual(
443        DebugStringGenerator.Serialize(sdt),
444        DebugStringGenerator.Serialize(o));
445    }
446
447    [TestMethod]
448    public void MultiDimensionalArray() {
449      string[,] mDimString = new string[,] {
450        {"ora", "et", "labora"},
451        {"Beten", "und", "Arbeiten"}
452      };
453      XmlGenerator.Serialize(mDimString, tempFile);
454      object o = XmlParser.Deserialize(tempFile);
455      Assert.AreEqual(
456        DebugStringGenerator.Serialize(mDimString),
457        DebugStringGenerator.Serialize(o));
458    }
459
460    [StorableClass]
461    public class NestedType {
462      [Storable]
463      private string value = "value";
464      public override bool Equals(object obj) {
465        NestedType nt = obj as NestedType;
466        if (nt == null)
467          throw new NotSupportedException();
468        return nt.value == value;
469      }
470      public override int GetHashCode() {
471        return value.GetHashCode();
472      }
473    }
474
475    [TestMethod]
476    public void NestedTypeTest() {
477      NestedType t = new NestedType();
478      XmlGenerator.Serialize(t, tempFile);
479      object o = XmlParser.Deserialize(tempFile);
480      Assert.AreEqual(
481        DebugStringGenerator.Serialize(t),
482        DebugStringGenerator.Serialize(o));
483      Assert.IsTrue(t.Equals(o));
484    }
485
486
487    [TestMethod]
488    public void SimpleArray() {
489      string[] strings = { "ora", "et", "labora" };
490      XmlGenerator.Serialize(strings, tempFile);
491      object o = XmlParser.Deserialize(tempFile);
492      Assert.AreEqual(
493        DebugStringGenerator.Serialize(strings),
494        DebugStringGenerator.Serialize(o));
495    }
496
497    [TestMethod]
498    public void PrimitiveRoot() {
499      XmlGenerator.Serialize(12.3f, tempFile);
500      object o = XmlParser.Deserialize(tempFile);
501      Assert.AreEqual(
502        DebugStringGenerator.Serialize(12.3f),
503        DebugStringGenerator.Serialize(o));
504    }
505
506    private string formatFullMemberName(MemberInfo mi) {
507      return new StringBuilder()
508        .Append(mi.DeclaringType.Assembly.GetName().Name)
509        .Append(": ")
510        .Append(mi.DeclaringType.Namespace)
511        .Append('.')
512        .Append(mi.DeclaringType.Name)
513        .Append('.')
514        .Append(mi.Name).ToString();
515    }
516
517    [TestMethod]
518    public void CodingConventions() {
519      List<string> lowerCaseMethodNames = new List<string>();
520      List<string> lowerCaseProperties = new List<string>();
521      List<string> lowerCaseFields = new List<string>();
522      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
523        if (!a.GetName().Name.StartsWith("HeuristicLab"))
524          continue;
525        foreach (Type t in a.GetTypes()) {
526          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
527            if (mi.DeclaringType.Name.StartsWith("<>"))
528              continue;
529            if (char.IsLower(mi.Name[0])) {
530              if (mi.MemberType == MemberTypes.Field)
531                lowerCaseFields.Add(formatFullMemberName(mi));
532              if (mi.MemberType == MemberTypes.Property)
533                lowerCaseProperties.Add(formatFullMemberName(mi));
534              if (mi.MemberType == MemberTypes.Method &&
535                !mi.Name.StartsWith("get_") &&
536                !mi.Name.StartsWith("set_") &&
537                !mi.Name.StartsWith("add_") &&
538                !mi.Name.StartsWith("remove_"))
539                lowerCaseMethodNames.Add(formatFullMemberName(mi));
540            }
541          }
542        }
543      }
544      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
545      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
546      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
547    }
548
549    [TestMethod]
550    public void Number2StringDecomposer() {
551      NumberTest sdt = new NumberTest();
552      XmlGenerator.Serialize(sdt, tempFile,
553        new Configuration(new XmlFormat(),
554          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
555          new List<ICompositeSerializer> {
556            new StorableSerializer(),
557            new Number2StringSerializer() }));
558      object o = XmlParser.Deserialize(tempFile);
559      Assert.AreEqual(
560        DebugStringGenerator.Serialize(sdt),
561        DebugStringGenerator.Serialize(o));
562      Assert.IsTrue(sdt.Equals(o));
563    }
564
565    [TestMethod]
566    public void Enums() {
567      EnumTest et = new EnumTest();
568      et.simpleEnum = SimpleEnum.two;
569      et.complexEnum = ComplexEnum.three;
570      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
571      XmlGenerator.Serialize(et, tempFile);
572      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
573      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
574      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
575      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
576    }
577
578    [TestMethod]
579    public void TestAliasingWithOverriddenEquals() {
580      List<IntWrapper> ints = new List<IntWrapper>();
581      ints.Add(new IntWrapper(1));
582      ints.Add(new IntWrapper(1));
583      Assert.AreEqual(ints[0], ints[1]);
584      Assert.AreNotSame(ints[0], ints[1]);
585      XmlGenerator.Serialize(ints, tempFile);
586      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
587      Assert.AreEqual(newInts[0].Value, 1);
588      Assert.AreEqual(newInts[1].Value, 1);
589      Assert.AreEqual(newInts[0], newInts[1]);
590      Assert.AreNotSame(newInts[0], newInts[1]);
591    }
592
593    [TestMethod]
594    public void NonDefaultConstructorTest() {
595      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
596      try {
597        XmlGenerator.Serialize(c, tempFile);
598        Assert.Fail("Exception not thrown");
599      } catch (PersistenceException) {
600      }
601    }
602
603    [TestMethod]
604    public void TestSavingException() {
605      List<int> list = new List<int> { 1, 2, 3 };
606      XmlGenerator.Serialize(list, tempFile);
607      NonSerializable s = new NonSerializable();
608      try {
609        XmlGenerator.Serialize(s, tempFile);
610        Assert.Fail("Exception expected");
611      } catch (PersistenceException) { }
612      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
613      Assert.AreEqual(list[0], newList[0]);
614      Assert.AreEqual(list[1], newList[1]);
615    }
616
617    [TestMethod]
618    public void TestTypeStringConversion() {
619      string name = typeof(List<int>[]).AssemblyQualifiedName;
620      string shortName =
621        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
622      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
623      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
624      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
625    }
626
627    [TestMethod]
628    public void TestHexadecimalPublicKeyToken() {
629      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
630      string shortName = "TestClass, TestAssembly";
631      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
632      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
633    }
634
635    [TestMethod]
636    public void TestMultipleFailure() {
637      List<NonSerializable> l = new List<NonSerializable>();
638      l.Add(new NonSerializable());
639      l.Add(new NonSerializable());
640      l.Add(new NonSerializable());
641      try {
642        Serializer s = new Serializer(l,
643          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
644          "ROOT", true);
645        StringBuilder tokens = new StringBuilder();
646        foreach (var token in s) {
647          tokens.Append(token.ToString());
648        }
649        Assert.Fail("Exception expected");
650      } catch (PersistenceException px) {
651        Assert.AreEqual(3, px.Data.Count);
652      }
653    }
654
655    [TestMethod]
656    public void TestAssemblyVersionCheck() {
657      IntWrapper i = new IntWrapper(1);
658      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
659      XmlGenerator g = new XmlGenerator();
660      StringBuilder dataString = new StringBuilder();
661      foreach (var token in s) {
662        dataString.Append(g.Format(token));
663      }
664      StringBuilder typeString = new StringBuilder();
665      foreach (var line in g.Format(s.TypeCache))
666        typeString.Append(line);
667      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
668      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
669      IntWrapper newI = (IntWrapper)d.Deserialize(p);
670      Assert.AreEqual(i.Value, newI.Value);
671
672      string newTypeString = Regex.Replace(typeString.ToString(),
673        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
674        "Version=0.0.9999.9999");
675      try {
676        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
677        Assert.Fail("Exception expected");
678      } catch (PersistenceException x) {
679        Assert.IsTrue(x.Message.Contains("incompatible"));
680      }
681      newTypeString = Regex.Replace(typeString.ToString(),
682        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
683        "Version=$1.9999.9999");
684      try {
685        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
686        Assert.Fail("Exception expected");
687      } catch (PersistenceException x) {
688        Assert.IsTrue(x.Message.Contains("newer"));
689      }
690    }
691
692    [TestMethod]
693    public void InheritanceTest() {
694      New n = new New();
695      XmlGenerator.Serialize(n, tempFile);
696      New nn = (New)XmlParser.Deserialize(tempFile);
697      Assert.AreEqual(n.Name, nn.Name);
698      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
699    }
700
701    [StorableClass]
702    class Child {
703      [Storable]
704      public GrandParent grandParent;
705    }
706
707    [StorableClass]
708    class Parent {
709      [Storable]
710      public Child child;
711    }
712
713    [StorableClass]
714    class GrandParent {
715      [Storable]
716      public Parent parent;
717    }
718
719    [TestMethod]
720    public void InstantiateParentChainReference() {
721      GrandParent gp = new GrandParent();
722      gp.parent = new Parent();
723      gp.parent.child = new Child();
724      gp.parent.child.grandParent = gp;
725      Assert.AreSame(gp, gp.parent.child.grandParent);
726      XmlGenerator.Serialize(gp, tempFile);
727      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
728      Assert.AreSame(newGp, newGp.parent.child.grandParent);
729    }
730
731    struct TestStruct {
732      int value;
733      int PropertyValue { get; set; }
734      public TestStruct(int value)
735        : this() {
736        this.value = value;
737        PropertyValue = value;
738      }
739    }
740
741    [TestMethod]
742    public void StructTest() {
743      TestStruct s = new TestStruct(10);
744      XmlGenerator.Serialize(s, tempFile);
745      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
746      Assert.AreEqual(s, newS);
747    }
748
749    [TestMethod]
750    public void PointTest() {
751      Point p = new Point(12, 34);
752      XmlGenerator.Serialize(p, tempFile);
753      Point newP = (Point)XmlParser.Deserialize(tempFile);
754      Assert.AreEqual(p, newP);
755    }
756
757    [TestMethod]
758    public void NullableValueTypes() {
759      double?[] d = new double?[] { null, 1, 2, 3 };
760      XmlGenerator.Serialize(d, tempFile);
761      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
762      Assert.AreEqual(d[0], newD[0]);
763      Assert.AreEqual(d[1], newD[1]);
764      Assert.AreEqual(d[2], newD[2]);
765      Assert.AreEqual(d[3], newD[3]);
766    }
767
768    [TestMethod]
769    public void BitmapTest() {
770      Icon icon = System.Drawing.SystemIcons.Hand;
771      Bitmap bitmap = icon.ToBitmap();
772      XmlGenerator.Serialize(bitmap, tempFile);
773      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
774
775      Assert.AreEqual(bitmap.Size, newBitmap.Size);
776      for(int i=0; i< bitmap.Size.Width; i++)
777        for(int j =0; j< bitmap.Size.Height; j++)
778          Assert.AreEqual(bitmap.GetPixel(i,j),newBitmap.GetPixel(i,j));
779    }
780
781    [StorableClass]
782    private class PersistenceHooks {
783      [Storable]
784      public int a;
785      [Storable]
786      public int b;
787      public int sum;
788      public bool WasSerialized { get; private set; }
789      [StorableHook(HookType.BeforeSerialization)]
790      void PreSerializationHook() {
791        WasSerialized = true;
792      }
793      [StorableHook(HookType.AfterDeserialization)]
794      void PostDeserializationHook() {
795        sum = a + b;
796      }
797    }
798
799    [TestMethod]
800    public void HookTest() {
801      PersistenceHooks hookTest = new PersistenceHooks();
802      hookTest.a = 2;
803      hookTest.b = 5;
804      Assert.IsFalse(hookTest.WasSerialized);
805      Assert.AreEqual(hookTest.sum, 0);
806      XmlGenerator.Serialize(hookTest, tempFile);
807      Assert.IsTrue(hookTest.WasSerialized);
808      Assert.AreEqual(hookTest.sum, 0);
809      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
810      Assert.AreEqual(newHookTest.a, hookTest.a);
811      Assert.AreEqual(newHookTest.b, hookTest.b);
812      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
813      Assert.IsFalse(newHookTest.WasSerialized);
814    }
815   
816    [StorableClass]
817    private class CustomConstructor {
818      public string Value = "none";
819      public CustomConstructor() {
820        Value = "default";
821      }
822      [StorableConstructor]
823      private CustomConstructor(bool deserializing) {
824        Assert.IsTrue(deserializing);
825        Value = "persistence";
826      }
827    }
828
829    [TestMethod]
830    public void TestCustomConstructor() {
831      CustomConstructor cc = new CustomConstructor();
832      Assert.AreEqual(cc.Value, "default");
833      XmlGenerator.Serialize(cc, tempFile);
834      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
835      Assert.AreEqual(newCC.Value, "persistence");
836    }
837
838    [StorableClass]
839    public class ExplodingDefaultConstructor {
840      public ExplodingDefaultConstructor() {
841        throw new Exception("this constructor will always fail");
842      }
843      public ExplodingDefaultConstructor(string password) {
844      }
845    }
846
847    [TestMethod]
848    public void TestConstructorExceptionUnwrapping() {
849      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
850      XmlGenerator.Serialize(x, tempFile);
851      try {
852        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
853        Assert.Fail("Exception expected");
854      } catch (PersistenceException pe) {
855        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
856      }
857    }
858
859    [TestMethod]
860    public void TestRejectionJustifications() {
861      NonSerializable ns = new NonSerializable();
862      try {
863        XmlGenerator.Serialize(ns, tempFile);
864        Assert.Fail("PersistenceException expected");
865      } catch (PersistenceException x) {
866        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));       
867      }
868    }
869
870    [TestMethod]
871    public void TestStreaming() {
872      using (MemoryStream stream = new MemoryStream()) {
873        Root r = InitializeComplexStorable();
874        XmlGenerator.Serialize(r, stream);
875        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
876          Root newR = (Root)XmlParser.Deserialize(stream2);
877          CompareComplexStorables(r, newR);
878        }
879      }
880    }
881
882    [StorableClass]
883    public class HookInheritanceTestBase {
884      [Storable]
885      public object a;
886      public object link;
887      [StorableHook(HookType.AfterDeserialization)]
888      private void relink() {
889        link = a;
890      }
891    }
892
893    [StorableClass]
894    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
895      [Storable]
896      public object b;
897      [StorableHook(HookType.AfterDeserialization)]
898      private void relink() {
899        Assert.AreSame(a, link);
900        link = b;
901      }
902    }
903
904    [TestMethod]
905    public void TestLinkInheritance() {
906      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
907      c.a = new object();
908      XmlGenerator.Serialize(c, tempFile);
909      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
910      Assert.AreSame(c.b, c.link);
911    }
912
913    [StorableClass(StorableClassType.AllFields)]
914    public class AllFieldsStorable {
915      public int Value1 = 1;
916      [Storable]
917      public int Value2 = 2;
918      public int Value3 { get; private set; }
919      public int Value4 { get; private set; }
920      [StorableConstructor]
921      public AllFieldsStorable(bool isDeserializing) {
922        if (!isDeserializing) {
923          Value1 = 12;
924          Value2 = 23;
925          Value3 = 34;
926          Value4 = 56;
927        }
928      }
929    }
930
931    [TestMethod]
932    public void TestStorableClassDiscoveryAllFields() {
933      AllFieldsStorable afs = new AllFieldsStorable(false);
934      XmlGenerator.Serialize(afs, tempFile);
935      AllFieldsStorable newAfs = (AllFieldsStorable)XmlParser.Deserialize(tempFile);
936      Assert.AreEqual(afs.Value1, newAfs.Value1);
937      Assert.AreEqual(afs.Value2, newAfs.Value2);
938      Assert.AreEqual(0, newAfs.Value3);
939      Assert.AreEqual(0, newAfs.Value4);
940    }
941
942    [StorableClass(StorableClassType.AllProperties)]
943    public class AllPropertiesStorable {
944      public int Value1 = 1;
945      [Storable]
946      public int Value2 = 2;
947      public int Value3 { get; private set; }
948      public int Value4 { get; private set; }
949      [StorableConstructor]
950      public AllPropertiesStorable(bool isDeserializing) {
951        if (!isDeserializing) {
952          Value1 = 12;
953          Value2 = 23;
954          Value3 = 34;
955          Value4 = 56;
956        }
957      }
958    }
959
960    [TestMethod]
961    public void TestStorableClassDiscoveryAllProperties() {
962      AllPropertiesStorable afs = new AllPropertiesStorable(false);
963      XmlGenerator.Serialize(afs, tempFile);
964      AllPropertiesStorable newAfs = (AllPropertiesStorable)XmlParser.Deserialize(tempFile);
965      Assert.AreEqual(1, newAfs.Value1);
966      Assert.AreEqual(2, newAfs.Value2);
967      Assert.AreEqual(afs.Value3, newAfs.Value3);
968      Assert.AreEqual(afs.Value4, newAfs.Value4);
969     
970    }
971
972    [StorableClass(StorableClassType.AllFieldsAndAllProperties)]
973    public class AllFieldsAndAllPropertiesStorable {
974      public int Value1 = 1;
975      [Storable]
976      public int Value2 = 2;
977      public int Value3 { get; private set; }
978      public int Value4 { get; private set; }
979      [StorableConstructor]
980      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
981        if (!isDeserializing) {
982          Value1 = 12;
983          Value2 = 23;
984          Value3 = 34;
985          Value4 = 56;
986        }
987      }
988    }
989
990    [TestMethod]
991    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
992      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
993      XmlGenerator.Serialize(afs, tempFile);
994      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)XmlParser.Deserialize(tempFile);
995      Assert.AreEqual(afs.Value1, newAfs.Value1);
996      Assert.AreEqual(afs.Value2, newAfs.Value2);
997      Assert.AreEqual(afs.Value3, newAfs.Value3);
998      Assert.AreEqual(afs.Value4, newAfs.Value4);     
999    }
1000
1001    [StorableClass(StorableClassType.MarkedOnly)]
1002    public class MarkedOnlyStorable {
1003      public int Value1 = 1;
1004      [Storable]
1005      public int Value2 = 2;
1006      public int Value3 { get; private set; }
1007      public int Value4 { get; private set; }
1008      [StorableConstructor]
1009      public MarkedOnlyStorable(bool isDeserializing) {
1010        if (!isDeserializing) {
1011          Value1 = 12;
1012          Value2 = 23;
1013          Value3 = 34;
1014          Value4 = 56;
1015        }
1016      }
1017    }
1018
1019    [TestMethod]
1020    public void TestStorableClassDiscoveryMarkedOnly() {
1021      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1022      XmlGenerator.Serialize(afs, tempFile);
1023      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
1024      Assert.AreEqual(1, newAfs.Value1);     
1025      Assert.AreEqual(afs.Value2, newAfs.Value2);
1026      Assert.AreEqual(0, newAfs.Value3);
1027      Assert.AreEqual(0, newAfs.Value4);
1028    }
1029
1030    [TestMethod]
1031    public void TestLineEndings() {
1032      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1033      List<string> lines = new List<string>();
1034      foreach (var br in lineBreaks)
1035        lines.Add("line1" + br + "line2");
1036      XmlGenerator.Serialize(lines, tempFile);
1037      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
1038      Assert.AreEqual(lines.Count, newLines.Count);
1039      for (int i = 0; i < lineBreaks.Count; i++) {
1040        Assert.AreEqual(lines[i], newLines[i]);
1041      }
1042    }
1043
1044    [TestMethod]
1045    public void TestSpecialNumbers() {
1046      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1047      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1048      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1049      Assert.IsTrue(double.IsNaN(specials[2]));
1050      XmlGenerator.Serialize(specials, tempFile);
1051      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
1052      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1053      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1054      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1055    }
1056   
1057
1058    [ClassInitialize]
1059    public static void Initialize(TestContext testContext) {
1060      ConfigurationService.Instance.Reset();
1061    }
1062  }
1063}
Note: See TracBrowser for help on using the repository browser.