Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Persistence/3.3/Tests/UseCases.cs @ 6228

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

check hooks by method name only (#1530)

File size: 40.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Drawing;
26using System.IO;
27using System.Linq;
28using System.Reflection;
29using System.Text;
30using System.Text.RegularExpressions;
31using HeuristicLab.Persistence.Auxiliary;
32using HeuristicLab.Persistence.Core;
33using HeuristicLab.Persistence.Core.Tokens;
34using HeuristicLab.Persistence.Default.CompositeSerializers;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.Persistence.Default.DebugString;
37using HeuristicLab.Persistence.Default.Xml;
38using HeuristicLab.Persistence.Default.Xml.Primitive;
39using HeuristicLab.Persistence.Interfaces;
40using Microsoft.VisualStudio.TestTools.UnitTesting;
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    [TestMethod]
293    public void ComplexEasyStorable() {
294      Root r = InitializeComplexStorable();
295      ReadableXmlGenerator.Serialize(r, tempFile);
296      using (var reader = new StreamReader(tempFile)) {
297        string text = reader.ReadToEnd();
298        Assert.IsTrue(text.StartsWith("<Root"));
299      }
300    }
301
302    private static void CompareComplexStorables(Root r, Root newR) {
303      Assert.AreEqual(
304        DebugStringGenerator.Serialize(r),
305        DebugStringGenerator.Serialize(newR));
306      Assert.AreSame(newR, newR.selfReferences[0]);
307      Assert.AreNotSame(r, newR);
308      Assert.AreEqual(r.myEnum, TestEnum.va1);
309      Assert.AreEqual(r.i[0], 7);
310      Assert.AreEqual(r.i[1], 5);
311      Assert.AreEqual(r.i[2], 6);
312      Assert.AreEqual(r.s, "new value");
313      Assert.AreEqual(r.intArray[0], 3);
314      Assert.AreEqual(r.intArray[1], 2);
315      Assert.AreEqual(r.intArray[2], 1);
316      Assert.AreEqual(r.intList[0], 9);
317      Assert.AreEqual(r.intList[1], 8);
318      Assert.AreEqual(r.intList[2], 7);
319      Assert.AreEqual(r.multiDimArray[0, 0], 5);
320      Assert.AreEqual(r.multiDimArray[0, 1], 4);
321      Assert.AreEqual(r.multiDimArray[0, 2], 3);
322      Assert.AreEqual(r.multiDimArray[1, 0], 1);
323      Assert.AreEqual(r.multiDimArray[1, 1], 4);
324      Assert.AreEqual(r.multiDimArray[1, 2], 6);
325      Assert.IsFalse(r.boolean);
326      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
327      Assert.AreEqual(r.kvp.Key, "string key");
328      Assert.AreEqual(r.kvp.Value, 321);
329      Assert.IsNull(r.uninitialized);
330      Assert.AreEqual(newR.myEnum, TestEnum.va1);
331      Assert.AreEqual(newR.i[0], 7);
332      Assert.AreEqual(newR.i[1], 5);
333      Assert.AreEqual(newR.i[2], 6);
334      Assert.AreEqual(newR.s, "new value");
335      Assert.AreEqual(newR.intArray[0], 3);
336      Assert.AreEqual(newR.intArray[1], 2);
337      Assert.AreEqual(newR.intArray[2], 1);
338      Assert.AreEqual(newR.intList[0], 9);
339      Assert.AreEqual(newR.intList[1], 8);
340      Assert.AreEqual(newR.intList[2], 7);
341      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
342      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
343      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
344      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
345      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
346      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
347      Assert.AreEqual(newR.intStack.Pop(), 3);
348      Assert.AreEqual(newR.intStack.Pop(), 2);
349      Assert.AreEqual(newR.intStack.Pop(), 1);
350      Assert.IsFalse(newR.boolean);
351      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
352      Assert.AreEqual(newR.kvp.Key, "string key");
353      Assert.AreEqual(newR.kvp.Value, 321);
354      Assert.IsNull(newR.uninitialized);
355    }
356
357    private static Root InitializeComplexStorable() {
358      Root r = new Root();
359      r.intStack.Push(1);
360      r.intStack.Push(2);
361      r.intStack.Push(3);
362      r.selfReferences = new List<Root> { r, r };
363      r.c = new Custom { r = r };
364      r.dict.Add("one", 1);
365      r.dict.Add("two", 2);
366      r.dict.Add("three", 3);
367      r.myEnum = TestEnum.va1;
368      r.i = new[] { 7, 5, 6 };
369      r.s = "new value";
370      r.intArray = new ArrayList { 3, 2, 1 };
371      r.intList = new List<int> { 9, 8, 7 };
372      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
373      r.boolean = false;
374      r.dateTime = DateTime.Now;
375      r.kvp = new KeyValuePair<string, int>("string key", 321);
376      r.uninitialized = null;
377
378      return r;
379    }
380
381    [TestMethod]
382    public void SelfReferences() {
383      C c = new C();
384      C[][] cs = new C[2][];
385      cs[0] = new C[] { c };
386      cs[1] = new C[] { c };
387      c.allCs = cs;
388      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
389      XmlGenerator.Serialize(cs, tempFile);
390      object o = XmlParser.Deserialize(tempFile);
391      Assert.AreEqual(
392        DebugStringGenerator.Serialize(cs),
393        DebugStringGenerator.Serialize(o));
394      Assert.AreSame(c, c.allCs[0][0]);
395      Assert.AreSame(c, c.allCs[1][0]);
396      Assert.AreSame(c, c.kvpList.Key[0]);
397      Assert.AreSame(c, c.kvpList.Value);
398      C[][] newCs = (C[][])o;
399      C newC = newCs[0][0];
400      Assert.AreSame(newC, newC.allCs[0][0]);
401      Assert.AreSame(newC, newC.allCs[1][0]);
402      Assert.AreSame(newC, newC.kvpList.Key[0]);
403      Assert.AreSame(newC, newC.kvpList.Value);
404    }
405
406    [TestMethod]
407    public void ArrayCreation() {
408      ArrayList[] arrayListArray = new ArrayList[4];
409      arrayListArray[0] = new ArrayList();
410      arrayListArray[0].Add(arrayListArray);
411      arrayListArray[0].Add(arrayListArray);
412      arrayListArray[1] = new ArrayList();
413      arrayListArray[1].Add(arrayListArray);
414      arrayListArray[2] = new ArrayList();
415      arrayListArray[2].Add(arrayListArray);
416      arrayListArray[2].Add(arrayListArray);
417      Array a = Array.CreateInstance(
418                              typeof(object),
419                              new[] { 1, 2 }, new[] { 3, 4 });
420      arrayListArray[2].Add(a);
421      XmlGenerator.Serialize(arrayListArray, tempFile);
422      object o = XmlParser.Deserialize(tempFile);
423      Assert.AreEqual(
424        DebugStringGenerator.Serialize(arrayListArray),
425        DebugStringGenerator.Serialize(o));
426      ArrayList[] newArray = (ArrayList[])o;
427      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
428      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
429      Assert.AreSame(newArray, newArray[0][0]);
430      Assert.AreSame(newArray, newArray[2][1]);
431    }
432
433    [TestMethod]
434    public void CustomSerializationProperty() {
435      Manager m = new Manager();
436      XmlGenerator.Serialize(m, tempFile);
437      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
438      Assert.AreNotEqual(
439        DebugStringGenerator.Serialize(m),
440        DebugStringGenerator.Serialize(newM));
441      Assert.AreEqual(m.dbl, newM.dbl);
442      Assert.AreEqual(m.lastLoadTime, new DateTime());
443      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
444      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
445    }
446
447    [TestMethod]
448    public void Primitives() {
449      PrimitivesTest sdt = new PrimitivesTest();
450      XmlGenerator.Serialize(sdt, tempFile);
451      object o = XmlParser.Deserialize(tempFile);
452      Assert.AreEqual(
453        DebugStringGenerator.Serialize(sdt),
454        DebugStringGenerator.Serialize(o));
455    }
456
457    [TestMethod]
458    public void MultiDimensionalArray() {
459      string[,] mDimString = new string[,] {
460        {"ora", "et", "labora"},
461        {"Beten", "und", "Arbeiten"}
462      };
463      XmlGenerator.Serialize(mDimString, tempFile);
464      object o = XmlParser.Deserialize(tempFile);
465      Assert.AreEqual(
466        DebugStringGenerator.Serialize(mDimString),
467        DebugStringGenerator.Serialize(o));
468    }
469
470    [StorableClass]
471    public class NestedType {
472      [Storable]
473      private string value = "value";
474      public override bool Equals(object obj) {
475        NestedType nt = obj as NestedType;
476        if (nt == null)
477          throw new NotSupportedException();
478        return nt.value == value;
479      }
480      public override int GetHashCode() {
481        return value.GetHashCode();
482      }
483    }
484
485    [TestMethod]
486    public void NestedTypeTest() {
487      NestedType t = new NestedType();
488      XmlGenerator.Serialize(t, tempFile);
489      object o = XmlParser.Deserialize(tempFile);
490      Assert.AreEqual(
491        DebugStringGenerator.Serialize(t),
492        DebugStringGenerator.Serialize(o));
493      Assert.IsTrue(t.Equals(o));
494    }
495
496
497    [TestMethod]
498    public void SimpleArray() {
499      string[] strings = { "ora", "et", "labora" };
500      XmlGenerator.Serialize(strings, tempFile);
501      object o = XmlParser.Deserialize(tempFile);
502      Assert.AreEqual(
503        DebugStringGenerator.Serialize(strings),
504        DebugStringGenerator.Serialize(o));
505    }
506
507    [TestMethod]
508    public void PrimitiveRoot() {
509      XmlGenerator.Serialize(12.3f, tempFile);
510      object o = XmlParser.Deserialize(tempFile);
511      Assert.AreEqual(
512        DebugStringGenerator.Serialize(12.3f),
513        DebugStringGenerator.Serialize(o));
514    }
515
516    private string formatFullMemberName(MemberInfo mi) {
517      return new StringBuilder()
518        .Append(mi.DeclaringType.Assembly.GetName().Name)
519        .Append(": ")
520        .Append(mi.DeclaringType.Namespace)
521        .Append('.')
522        .Append(mi.DeclaringType.Name)
523        .Append('.')
524        .Append(mi.Name).ToString();
525    }
526
527    [TestMethod]
528    public void CodingConventions() {
529      List<string> lowerCaseMethodNames = new List<string>();
530      List<string> lowerCaseProperties = new List<string>();
531      List<string> lowerCaseFields = new List<string>();
532      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
533        if (!a.GetName().Name.StartsWith("HeuristicLab"))
534          continue;
535        foreach (Type t in a.GetTypes()) {
536          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
537            if (mi.DeclaringType.Name.StartsWith("<>"))
538              continue;
539            if (char.IsLower(mi.Name[0])) {
540              if (mi.MemberType == MemberTypes.Field)
541                lowerCaseFields.Add(formatFullMemberName(mi));
542              if (mi.MemberType == MemberTypes.Property)
543                lowerCaseProperties.Add(formatFullMemberName(mi));
544              if (mi.MemberType == MemberTypes.Method &&
545                !mi.Name.StartsWith("get_") &&
546                !mi.Name.StartsWith("set_") &&
547                !mi.Name.StartsWith("add_") &&
548                !mi.Name.StartsWith("remove_"))
549                lowerCaseMethodNames.Add(formatFullMemberName(mi));
550            }
551          }
552        }
553      }
554      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
555      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
556      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
557    }
558
559    [TestMethod]
560    public void Number2StringDecomposer() {
561      NumberTest sdt = new NumberTest();
562      XmlGenerator.Serialize(sdt, tempFile,
563        new Configuration(new XmlFormat(),
564          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
565          new List<ICompositeSerializer> {
566            new StorableSerializer(),
567            new Number2StringSerializer() }));
568      object o = XmlParser.Deserialize(tempFile);
569      Assert.AreEqual(
570        DebugStringGenerator.Serialize(sdt),
571        DebugStringGenerator.Serialize(o));
572      Assert.IsTrue(sdt.Equals(o));
573    }
574
575    [TestMethod]
576    public void Enums() {
577      EnumTest et = new EnumTest();
578      et.simpleEnum = SimpleEnum.two;
579      et.complexEnum = ComplexEnum.three;
580      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
581      XmlGenerator.Serialize(et, tempFile);
582      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
583      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
584      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
585      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
586    }
587
588    [TestMethod]
589    public void TestAliasingWithOverriddenEquals() {
590      List<IntWrapper> ints = new List<IntWrapper>();
591      ints.Add(new IntWrapper(1));
592      ints.Add(new IntWrapper(1));
593      Assert.AreEqual(ints[0], ints[1]);
594      Assert.AreNotSame(ints[0], ints[1]);
595      XmlGenerator.Serialize(ints, tempFile);
596      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
597      Assert.AreEqual(newInts[0].Value, 1);
598      Assert.AreEqual(newInts[1].Value, 1);
599      Assert.AreEqual(newInts[0], newInts[1]);
600      Assert.AreNotSame(newInts[0], newInts[1]);
601    }
602
603    [TestMethod]
604    public void NonDefaultConstructorTest() {
605      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
606      try {
607        XmlGenerator.Serialize(c, tempFile);
608        Assert.Fail("Exception not thrown");
609      } catch (PersistenceException) {
610      }
611    }
612
613    [TestMethod]
614    public void TestSavingException() {
615      List<int> list = new List<int> { 1, 2, 3 };
616      XmlGenerator.Serialize(list, tempFile);
617      NonSerializable s = new NonSerializable();
618      try {
619        XmlGenerator.Serialize(s, tempFile);
620        Assert.Fail("Exception expected");
621      } catch (PersistenceException) { }
622      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
623      Assert.AreEqual(list[0], newList[0]);
624      Assert.AreEqual(list[1], newList[1]);
625    }
626
627    [TestMethod]
628    public void TestTypeStringConversion() {
629      string name = typeof(List<int>[]).AssemblyQualifiedName;
630      string shortName =
631        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
632      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
633      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
634      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
635    }
636
637    [TestMethod]
638    public void TestHexadecimalPublicKeyToken() {
639      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
640      string shortName = "TestClass, TestAssembly";
641      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
642      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
643    }
644
645    [TestMethod]
646    public void TestMultipleFailure() {
647      List<NonSerializable> l = new List<NonSerializable>();
648      l.Add(new NonSerializable());
649      l.Add(new NonSerializable());
650      l.Add(new NonSerializable());
651      try {
652        Serializer s = new Serializer(l,
653          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
654          "ROOT", true);
655        StringBuilder tokens = new StringBuilder();
656        foreach (var token in s) {
657          tokens.Append(token.ToString());
658        }
659        Assert.Fail("Exception expected");
660      } catch (PersistenceException px) {
661        Assert.AreEqual(3, px.Data.Count);
662      }
663    }
664
665    [TestMethod]
666    public void TestAssemblyVersionCheck() {
667      IntWrapper i = new IntWrapper(1);
668      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
669      XmlGenerator g = new XmlGenerator();
670      StringBuilder dataString = new StringBuilder();
671      foreach (var token in s) {
672        dataString.Append(g.Format(token));
673      }
674      StringBuilder typeString = new StringBuilder();
675      foreach (var line in g.Format(s.TypeCache))
676        typeString.Append(line);
677      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
678      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
679      IntWrapper newI = (IntWrapper)d.Deserialize(p);
680      Assert.AreEqual(i.Value, newI.Value);
681
682      string newTypeString = Regex.Replace(typeString.ToString(),
683        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
684        "Version=0.0.9999.9999");
685      try {
686        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
687        Assert.Fail("Exception expected");
688      } catch (PersistenceException x) {
689        Assert.IsTrue(x.Message.Contains("incompatible"));
690      }
691      newTypeString = Regex.Replace(typeString.ToString(),
692        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
693        "Version=$1.9999.9999");
694      try {
695        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
696        Assert.Fail("Exception expected");
697      } catch (PersistenceException x) {
698        Assert.IsTrue(x.Message.Contains("newer"));
699      }
700    }
701
702    [TestMethod]
703    public void InheritanceTest() {
704      New n = new New();
705      XmlGenerator.Serialize(n, tempFile);
706      New nn = (New)XmlParser.Deserialize(tempFile);
707      Assert.AreEqual(n.Name, nn.Name);
708      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
709    }
710
711    [StorableClass]
712    class Child {
713      [Storable]
714      public GrandParent grandParent;
715    }
716
717    [StorableClass]
718    class Parent {
719      [Storable]
720      public Child child;
721    }
722
723    [StorableClass]
724    class GrandParent {
725      [Storable]
726      public Parent parent;
727    }
728
729    [TestMethod]
730    public void InstantiateParentChainReference() {
731      GrandParent gp = new GrandParent();
732      gp.parent = new Parent();
733      gp.parent.child = new Child();
734      gp.parent.child.grandParent = gp;
735      Assert.AreSame(gp, gp.parent.child.grandParent);
736      XmlGenerator.Serialize(gp, tempFile);
737      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
738      Assert.AreSame(newGp, newGp.parent.child.grandParent);
739    }
740
741    struct TestStruct {
742      int value;
743      int PropertyValue { get; set; }
744      public TestStruct(int value)
745        : this() {
746        this.value = value;
747        PropertyValue = value;
748      }
749    }
750
751    [TestMethod]
752    public void StructTest() {
753      TestStruct s = new TestStruct(10);
754      XmlGenerator.Serialize(s, tempFile);
755      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
756      Assert.AreEqual(s, newS);
757    }
758
759    [TestMethod]
760    public void PointTest() {
761      Point p = new Point(12, 34);
762      XmlGenerator.Serialize(p, tempFile);
763      Point newP = (Point)XmlParser.Deserialize(tempFile);
764      Assert.AreEqual(p, newP);
765    }
766
767    [TestMethod]
768    public void NullableValueTypes() {
769      double?[] d = new double?[] { null, 1, 2, 3 };
770      XmlGenerator.Serialize(d, tempFile);
771      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
772      Assert.AreEqual(d[0], newD[0]);
773      Assert.AreEqual(d[1], newD[1]);
774      Assert.AreEqual(d[2], newD[2]);
775      Assert.AreEqual(d[3], newD[3]);
776    }
777
778    [TestMethod]
779    public void BitmapTest() {
780      Icon icon = System.Drawing.SystemIcons.Hand;
781      Bitmap bitmap = icon.ToBitmap();
782      XmlGenerator.Serialize(bitmap, tempFile);
783      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
784
785      Assert.AreEqual(bitmap.Size, newBitmap.Size);
786      for (int i = 0; i < bitmap.Size.Width; i++)
787        for (int j = 0; j < bitmap.Size.Height; j++)
788          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
789    }
790
791    [StorableClass]
792    private class PersistenceHooks {
793      [Storable]
794      public int a;
795      [Storable]
796      public int b;
797      public int sum;
798      public bool WasSerialized { get; private set; }
799      [StorableHook(HookType.BeforeSerialization)]
800      void BeforeSerialization() {
801        WasSerialized = true;
802      }
803      [StorableHook(HookType.AfterDeserialization)]
804      void AfterDeserialization() {
805        sum = a + b;
806      }
807    }
808
809    [TestMethod]
810    public void HookTest() {
811      PersistenceHooks hookTest = new PersistenceHooks();
812      hookTest.a = 2;
813      hookTest.b = 5;
814      Assert.IsFalse(hookTest.WasSerialized);
815      Assert.AreEqual(hookTest.sum, 0);
816      XmlGenerator.Serialize(hookTest, tempFile);
817      Assert.IsTrue(hookTest.WasSerialized);
818      Assert.AreEqual(hookTest.sum, 0);
819      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
820      Assert.AreEqual(newHookTest.a, hookTest.a);
821      Assert.AreEqual(newHookTest.b, hookTest.b);
822      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
823      Assert.IsFalse(newHookTest.WasSerialized);
824    }
825
826    [StorableClass]
827    private class CustomConstructor {
828      public string Value = "none";
829      public CustomConstructor() {
830        Value = "default";
831      }
832      [StorableConstructor]
833      private CustomConstructor(bool deserializing) {
834        Assert.IsTrue(deserializing);
835        Value = "persistence";
836      }
837    }
838
839    [TestMethod]
840    public void TestCustomConstructor() {
841      CustomConstructor cc = new CustomConstructor();
842      Assert.AreEqual(cc.Value, "default");
843      XmlGenerator.Serialize(cc, tempFile);
844      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
845      Assert.AreEqual(newCC.Value, "persistence");
846    }
847
848    [StorableClass]
849    public class ExplodingDefaultConstructor {
850      public ExplodingDefaultConstructor() {
851        throw new Exception("this constructor will always fail");
852      }
853      public ExplodingDefaultConstructor(string password) {
854      }
855    }
856
857    [TestMethod]
858    public void TestConstructorExceptionUnwrapping() {
859      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
860      XmlGenerator.Serialize(x, tempFile);
861      try {
862        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
863        Assert.Fail("Exception expected");
864      } catch (PersistenceException pe) {
865        Assert.AreEqual("this constructor will always fail", pe.InnerException.Message);
866      }
867    }
868
869    [TestMethod]
870    public void TestRejectionJustifications() {
871      NonSerializable ns = new NonSerializable();
872      try {
873        XmlGenerator.Serialize(ns, tempFile);
874        Assert.Fail("PersistenceException expected");
875      } catch (PersistenceException x) {
876        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
877      }
878    }
879
880    [TestMethod]
881    public void TestStreaming() {
882      using (MemoryStream stream = new MemoryStream()) {
883        Root r = InitializeComplexStorable();
884        XmlGenerator.Serialize(r, stream);
885        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
886          Root newR = (Root)XmlParser.Deserialize(stream2);
887          CompareComplexStorables(r, newR);
888        }
889      }
890    }
891
892    [StorableClass]
893    public class HookInheritanceTestBase {
894      [Storable]
895      public object a;
896      public object link;
897      [StorableHook(HookType.AfterDeserialization)]
898      private void AfterDeserialization() {
899        link = a;
900      }
901    }
902
903    [StorableClass]
904    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
905      [Storable]
906      public object b;
907      [StorableHook(HookType.AfterDeserialization)]
908      private void AfterDeserialization() {
909        Assert.AreSame(a, link);
910        link = b;
911      }
912    }
913
914    [TestMethod]
915    public void TestLinkInheritance() {
916      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
917      c.a = new object();
918      XmlGenerator.Serialize(c, tempFile);
919      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
920      Assert.AreSame(c.b, c.link);
921    }
922
923
924    [StorableClass]
925    public class MarkedOnlyStorable {
926      public int Value1 = 1;
927      [Storable]
928      public int Value2 = 2;
929      public int Value3 { get; private set; }
930      public int Value4 { get; private set; }
931      [StorableConstructor]
932      public MarkedOnlyStorable(bool isDeserializing) {
933        if (!isDeserializing) {
934          Value1 = 12;
935          Value2 = 23;
936          Value3 = 34;
937          Value4 = 56;
938        }
939      }
940    }
941
942    [TestMethod]
943    public void TestStorableClassDiscoveryMarkedOnly() {
944      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
945      XmlGenerator.Serialize(afs, tempFile);
946      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
947      Assert.AreEqual(1, newAfs.Value1);
948      Assert.AreEqual(afs.Value2, newAfs.Value2);
949      Assert.AreEqual(0, newAfs.Value3);
950      Assert.AreEqual(0, newAfs.Value4);
951    }
952
953    [TestMethod]
954    public void TestLineEndings() {
955      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
956      List<string> lines = new List<string>();
957      foreach (var br in lineBreaks)
958        lines.Add("line1" + br + "line2");
959      XmlGenerator.Serialize(lines, tempFile);
960      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
961      Assert.AreEqual(lines.Count, newLines.Count);
962      for (int i = 0; i < lineBreaks.Count; i++) {
963        Assert.AreEqual(lines[i], newLines[i]);
964      }
965    }
966
967    [TestMethod]
968    public void TestSpecialNumbers() {
969      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
970      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
971      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
972      Assert.IsTrue(double.IsNaN(specials[2]));
973      XmlGenerator.Serialize(specials, tempFile);
974      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
975      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
976      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
977      Assert.IsTrue(double.IsNaN(newSpecials[2]));
978    }
979
980    [TestMethod]
981    public void TestStringSplit() {
982      string s = "1.2;2.3;3.4;;;4.9";
983      var l = s.EnumerateSplit(';').ToList();
984      Assert.AreEqual("1.2", l[0]);
985      Assert.AreEqual("2.3", l[1]);
986      Assert.AreEqual("3.4", l[2]);
987      Assert.AreEqual("4.9", l[3]);
988    }
989
990    [TestMethod]
991    public void TestCompactNumberArraySerializer() {
992      Random r = new Random();
993      double[] a = new double[CompactNumberArray2StringSerializer.SPLIT_THRESHOLD * 2 + 1];
994      for (int i = 0; i < a.Length; i++)
995        a[i] = r.Next(10);
996      var config = ConfigurationService.Instance.GetDefaultConfig(new XmlFormat());
997      config = new Configuration(config.Format,
998        config.PrimitiveSerializers.Where(s => s.SourceType != typeof(double[])),
999        config.CompositeSerializers);
1000      XmlGenerator.Serialize(a, tempFile, config);
1001      double[] newA = XmlParser.Deserialize<double[]>(tempFile);
1002      Assert.AreEqual(a.Length, newA.Length);
1003      for (int i = 0; i < a.Rank; i++) {
1004        Assert.AreEqual(a.GetLength(i), newA.GetLength(i));
1005        Assert.AreEqual(a.GetLowerBound(i), newA.GetLowerBound(i));
1006      }
1007      for (int i = 0; i < a.Length; i++) {
1008        Assert.AreEqual(a[i], newA[i]);
1009      }
1010    }
1011    private class IdentityComparer<T> : IEqualityComparer<T> {
1012
1013      public bool Equals(T x, T y) {
1014        return x.Equals(y);
1015      }
1016
1017      public int GetHashCode(T obj) {
1018        return obj.GetHashCode();
1019      }
1020    }
1021
1022    [TestMethod]
1023    public void TestHashSetSerializer() {
1024      var hashSets = new List<HashSet<int>>() {
1025        new HashSet<int>(new[] { 1, 2, 3 }),
1026        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1027      };
1028      XmlGenerator.Serialize(hashSets, tempFile);
1029      var newHashSets = XmlParser.Deserialize<List<HashSet<int>>>(tempFile);
1030      Assert.IsTrue(newHashSets[0].Contains(1));
1031      Assert.IsTrue(newHashSets[0].Contains(2));
1032      Assert.IsTrue(newHashSets[0].Contains(3));
1033      Assert.IsTrue(newHashSets[1].Contains(4));
1034      Assert.IsTrue(newHashSets[1].Contains(5));
1035      Assert.IsTrue(newHashSets[1].Contains(6));
1036      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1037      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1038    }
1039
1040    [TestMethod]
1041    public void TestConcreteDictionarySerializer() {
1042      var dictionaries = new List<Dictionary<int, int>>() {
1043        new Dictionary<int, int>(),
1044        new Dictionary<int, int>(new IdentityComparer<int>()),
1045      };
1046      dictionaries[0].Add(1, 1);
1047      dictionaries[0].Add(2, 2);
1048      dictionaries[0].Add(3, 3);
1049      dictionaries[1].Add(4, 4);
1050      dictionaries[1].Add(5, 5);
1051      dictionaries[1].Add(6, 6);
1052      XmlGenerator.Serialize(dictionaries, tempFile, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1053      var newDictionaries = XmlParser.Deserialize<List<Dictionary<int, int>>>(tempFile);
1054      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1055      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1056      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1057      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1058      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1059      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1060      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1061      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1062      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1063      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1064      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1065      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1066      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1067      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1068    }
1069
1070    [StorableClass]
1071    public class ReadOnlyFail {
1072      [Storable]
1073      public string ReadOnly {
1074        get { return "fail"; }
1075      }
1076    }
1077
1078    [TestMethod]
1079    public void TestReadOnlyFail() {
1080      try {
1081        XmlGenerator.Serialize(new ReadOnlyFail(), tempFile);
1082        Assert.Fail("Exception expected");
1083      } catch (PersistenceException) {
1084      } catch {
1085        Assert.Fail("PersistenceException expected");
1086      }
1087    }
1088
1089
1090    [StorableClass]
1091    public class WriteOnlyFail {
1092      [Storable]
1093      public string WriteOnly {
1094        set { throw new InvalidOperationException("this property should never be set."); }
1095      }
1096    }
1097
1098    [TestMethod]
1099    public void TestWriteOnlyFail() {
1100      try {
1101        XmlGenerator.Serialize(new WriteOnlyFail(), tempFile);
1102        Assert.Fail("Exception expected");
1103      } catch (PersistenceException) {
1104      } catch {
1105        Assert.Fail("PersistenceException expected.");
1106      }
1107    }
1108
1109    [StorableClass]
1110    public class OneWayTest {
1111      public OneWayTest() { this.value = "default"; }
1112      public string value;
1113      [Storable(AllowOneWay=true)]
1114      public string ReadOnly {
1115        get { return "ReadOnly"; }
1116      }
1117      [Storable(AllowOneWay=true)]
1118      public string WriteOnly {
1119        set { this.value = value; }
1120      }
1121    }
1122
1123    [TestMethod]
1124    public void TestOneWaySerialization() {
1125      var test = new OneWayTest();
1126      var serializer = new Serializer(test, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1127      var it = serializer.GetEnumerator();
1128      it.MoveNext();
1129      Assert.AreEqual("ROOT", ((BeginToken)it.Current).Name); it.MoveNext();
1130      Assert.AreEqual("ReadOnly", ((PrimitiveToken)it.Current).Name); it.MoveNext();
1131      Assert.AreEqual("ROOT", ((EndToken)it.Current).Name); it.MoveNext();
1132      var deserializer = new Deserializer(new[] {
1133        new TypeMapping(0, typeof(OneWayTest).AssemblyQualifiedName, typeof(StorableSerializer).AssemblyQualifiedName),
1134        new TypeMapping(1, typeof(string).AssemblyQualifiedName, typeof(String2XmlSerializer).AssemblyQualifiedName) });
1135      var newTest = (OneWayTest)deserializer.Deserialize(new ISerializationToken[] {
1136        new BeginToken("ROOT", 0, 0),
1137        new PrimitiveToken("WriteOnly", 1, 1, new XmlString("<![CDATA[serial data]]>")),
1138        new EndToken("ROOT", 0, 0)
1139      });
1140      Assert.AreEqual("serial data", newTest.value);
1141    }
1142
1143    [TestMethod]
1144    public void TestTypeCacheExport() {
1145      var test = new List<List<int>>();
1146      test.Add(new List<int>() { 1, 2, 3 });
1147      IEnumerable<Type> types;
1148      using (var stream = new MemoryStream()) {
1149        XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1150      }
1151      List<Type> t = new List<Type>(types);
1152      // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1153      Assert.IsTrue(t.Contains(typeof(List<int>)));
1154      Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1155      Assert.AreEqual(t.Count, 2);
1156    }
1157
1158    [TestMethod]
1159    public void TupleTest() {
1160      var t1 = Tuple.Create(1);
1161      var t2 = Tuple.Create('1', "2");
1162      var t3 = Tuple.Create(3.0, 3f, 5);
1163      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1164      var tuple = Tuple.Create(t1, t2, t3, t4);
1165      XmlGenerator.Serialize(tuple, tempFile);
1166      var newTuple = XmlParser.Deserialize<Tuple<Tuple<int>, Tuple<char, string>, Tuple<double, float, int>, Tuple<Tuple<int, int, int>, Tuple<int, int, int>, Tuple<int, int, int>>>>(tempFile);
1167      Assert.AreEqual(tuple, newTuple);
1168    }
1169
1170
1171
1172    [ClassInitialize]
1173    public static void Initialize(TestContext testContext) {
1174      ConfigurationService.Instance.Reset();
1175    }
1176  }
1177}
Note: See TracBrowser for help on using the repository browser.