Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3623 was 3293, checked in by epitzer, 15 years ago

Replace XML reader to ensure proper parsing of line endings especially inside CDATA blocks (#548)

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