Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3037 was 3029, checked in by epitzer, 14 years ago

add support for automatic serialization of fields and properties (#548)

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