Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCases.cs @ 16374

Last change on this file since 16374 was 15857, checked in by jkarder, 7 years ago

#2520: worked on conversions

File size: 54.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Globalization;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30using System.Text;
31using System.Text.RegularExpressions;
32using System.Threading.Tasks;
33using HeuristicLab.Algorithms.GeneticAlgorithm;
34using HeuristicLab.Persistence.Auxiliary;
35using HeuristicLab.Persistence.Core;
36using HeuristicLab.Persistence.Core.Tokens;
37using HeuristicLab.Persistence.Default.CompositeSerializers;
38using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
39using HeuristicLab.Persistence.Default.DebugString;
40using HeuristicLab.Persistence.Default.Xml;
41using HeuristicLab.Persistence.Default.Xml.Primitive;
42using HeuristicLab.Persistence.Interfaces;
43using HeuristicLab.Tests;
44using Microsoft.VisualStudio.TestTools.UnitTesting;
45
46namespace HeuristicLab.Persistence.Tests {
47
48  [StorableType("8658966d-3731-4588-8a92-25740c677478")]
49  public class NumberTest {
50    [Storable]
51    private bool _bool = true;
52    [Storable]
53    private byte _byte = 0xFF;
54    [Storable]
55    private sbyte _sbyte = 0xF;
56    [Storable]
57    private short _short = -123;
58    [Storable]
59    private ushort _ushort = 123;
60    [Storable]
61    private int _int = -123;
62    [Storable]
63    private uint _uint = 123;
64    [Storable]
65    private long _long = 123456;
66    [Storable]
67    private ulong _ulong = 123456;
68    public override bool Equals(object obj) {
69      NumberTest nt = obj as NumberTest;
70      if (nt == null)
71        throw new NotSupportedException();
72      return
73        nt._bool == _bool &&
74        nt._byte == _byte &&
75        nt._sbyte == _sbyte &&
76        nt._short == _short &&
77        nt._ushort == _ushort &&
78        nt._int == _int &&
79        nt._uint == _uint &&
80        nt._long == _long &&
81        nt._ulong == _ulong;
82    }
83    public override int GetHashCode() {
84      return
85        _bool.GetHashCode() ^
86        _byte.GetHashCode() ^
87        _sbyte.GetHashCode() ^
88        _short.GetHashCode() ^
89        _short.GetHashCode() ^
90        _int.GetHashCode() ^
91        _uint.GetHashCode() ^
92        _long.GetHashCode() ^
93        _ulong.GetHashCode();
94    }
95  }
96
97  [StorableType("30315bb1-3cac-498f-9ff4-b27f0f6234a8")]
98  public class NonDefaultConstructorClass {
99    [Storable]
100    int value;
101    public NonDefaultConstructorClass(int value) {
102      this.value = value;
103    }
104  }
105
106  [StorableType("42019826-a9f7-4e78-b035-19292cd34d26")]
107  public class IntWrapper {
108
109    [Storable]
110    public int Value;
111
112    private IntWrapper() { }
113
114    public IntWrapper(int value) {
115      this.Value = value;
116    }
117
118    public override bool Equals(object obj) {
119      if (obj as IntWrapper == null)
120        return false;
121      return Value.Equals(((IntWrapper)obj).Value);
122    }
123    public override int GetHashCode() {
124      return Value.GetHashCode();
125    }
126
127  }
128
129  [StorableType("92810c22-155c-4e61-a3ec-79533e5d3c1e")]
130  public class PrimitivesTest : NumberTest {
131    [Storable]
132    private char c = 'e';
133    [Storable]
134    private long[,] _long_array =
135      new long[,] { { 123, 456, }, { 789, 123 } };
136    [Storable]
137    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
138    [Storable]
139    private object o = new object();
140    public override bool Equals(object obj) {
141      PrimitivesTest pt = obj as PrimitivesTest;
142      if (pt == null)
143        throw new NotSupportedException();
144      return base.Equals(obj) &&
145        c == pt.c &&
146        _long_array == pt._long_array &&
147        list == pt.list &&
148        o == pt.o;
149    }
150    public override int GetHashCode() {
151      return base.GetHashCode() ^
152        c.GetHashCode() ^
153        _long_array.GetHashCode() ^
154        list.GetHashCode() ^
155        o.GetHashCode();
156    }
157  }
158
159  [StorableType("09355759-308f-438d-95a1-63704159b833")]
160  public enum TestEnum { va1, va2, va3, va8 };
161
162  [StorableType("92efaa22-6ae0-4004-a0a8-7bfe397d25d0")]
163  public class RootBase {
164    [Storable]
165    private string baseString = "   Serial  ";
166    [Storable]
167    public TestEnum myEnum = TestEnum.va3;
168    public override bool Equals(object obj) {
169      RootBase rb = obj as RootBase;
170      if (rb == null)
171        throw new NotSupportedException();
172      return baseString == rb.baseString &&
173        myEnum == rb.myEnum;
174    }
175    public override int GetHashCode() {
176      return baseString.GetHashCode() ^
177        myEnum.GetHashCode();
178    }
179  }
180
181  [StorableType("26b42eae-7dbb-46bb-84b3-d50d357eec05")]
182  public class Root : RootBase {
183    [Storable]
184    public Stack<int> intStack = new Stack<int>();
185    [Storable]
186    public int[] i = new[] { 3, 4, 5, 6 };
187    [Storable(Name = "Test String")]
188    public string s;
189    [Storable]
190    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
191    [Storable]
192    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
193    [Storable]
194    public Custom c;
195    [Storable]
196    public List<Root> selfReferences;
197    [Storable]
198    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
199    [Storable]
200    public bool boolean = true;
201    [Storable]
202    public DateTime dateTime;
203    [Storable]
204    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
205    [Storable]
206    public Dictionary<string, int> dict = new Dictionary<string, int>();
207    [Storable(DefaultValue = "default")]
208    public string uninitialized;
209  }
210
211  [StorableType("b976a474-cae4-4f08-b425-e69977e1e4bf")]
212  public enum SimpleEnum { one, two, three }
213  [StorableType("4f41591b-e0be-42ae-af66-800c20d21356")]
214  public enum ComplexEnum { one = 1, two = 2, three = 3 }
215  [FlagsAttribute]
216  [StorableType("426bb2f4-7951-4378-a923-bc7a8ce56bd7")]
217  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
218
219  [StorableType("0fe878c9-35e6-4478-8cbe-438211b7a3a5")]
220  public class EnumTest {
221    [Storable]
222    public SimpleEnum simpleEnum = SimpleEnum.one;
223    [Storable]
224    public ComplexEnum complexEnum = (ComplexEnum)2;
225    [Storable]
226    public TrickyEnum trickyEnum = (TrickyEnum)15;
227  }
228
229  [StorableType("b83a36e8-7ba7-4ce4-82c3-602678c2a7a5")]
230  public class Custom {
231    [Storable]
232    public int i;
233    [Storable]
234    public Root r;
235    [Storable]
236    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
237  }
238
239  [StorableType("fe285830-9dc6-4b77-8f8b-3c09a02ef1e0")]
240  public class Manager {
241
242    public DateTime lastLoadTime;
243    [Storable]
244    private DateTime lastLoadTimePersistence {
245      get { return lastLoadTime; }
246      set { lastLoadTime = DateTime.Now; }
247    }
248    [Storable]
249    public double? dbl;
250  }
251
252  [StorableType("49551a89-6586-4ce1-8323-a8fd4409a0f6")]
253  public class C {
254    [Storable]
255    public C[][] allCs;
256    [Storable]
257    public KeyValuePair<List<C>, C> kvpList;
258  }
259
260  public class NonSerializable {
261    int x = 0;
262    public override bool Equals(object obj) {
263      NonSerializable ns = obj as NonSerializable;
264      if (ns == null)
265        throw new NotSupportedException();
266      return ns.x == x;
267    }
268    public override int GetHashCode() {
269      return x.GetHashCode();
270    }
271  }
272
273
274  [TestClass]
275  [StorableType("adca4c31-c835-4113-83aa-26a7a2cb3204")]
276  public class UseCases {
277
278    private string tempFile;
279
280    [TestInitialize()]
281    public void CreateTempFile() {
282      tempFile = Path.GetTempFileName();
283    }
284
285    [TestCleanup()]
286    public void ClearTempFile() {
287      StreamReader reader = new StreamReader(tempFile);
288      string s = reader.ReadToEnd();
289      reader.Close();
290      File.Delete(tempFile);
291    }
292
293    [TestMethod]
294    [TestCategory("Persistence")]
295    [TestProperty("Time", "short")]
296    public void ComplexStorable() {
297      Root r = InitializeComplexStorable();
298      XmlGenerator.Serialize(r, tempFile);
299      Root newR = (Root)XmlParser.Deserialize(tempFile);
300      CompareComplexStorables(r, newR);
301    }
302
303    [TestMethod]
304    [TestCategory("Persistence")]
305    [TestProperty("Time", "short")]
306    public void ComplexEasyStorable() {
307      Root r = InitializeComplexStorable();
308      ReadableXmlGenerator.Serialize(r, tempFile);
309      using (var reader = new StreamReader(tempFile)) {
310        string text = reader.ReadToEnd();
311        Assert.IsTrue(text.StartsWith("<Root"));
312      }
313    }
314
315    private static void CompareComplexStorables(Root r, Root newR) {
316      Assert.AreEqual(
317        DebugStringGenerator.Serialize(r),
318        DebugStringGenerator.Serialize(newR));
319      Assert.AreSame(newR, newR.selfReferences[0]);
320      Assert.AreNotSame(r, newR);
321      Assert.AreEqual(r.myEnum, TestEnum.va1);
322      Assert.AreEqual(r.i[0], 7);
323      Assert.AreEqual(r.i[1], 5);
324      Assert.AreEqual(r.i[2], 6);
325      Assert.AreEqual(r.s, "new value");
326      Assert.AreEqual(r.intArray[0], 3);
327      Assert.AreEqual(r.intArray[1], 2);
328      Assert.AreEqual(r.intArray[2], 1);
329      Assert.AreEqual(r.intList[0], 9);
330      Assert.AreEqual(r.intList[1], 8);
331      Assert.AreEqual(r.intList[2], 7);
332      Assert.AreEqual(r.multiDimArray[0, 0], 5);
333      Assert.AreEqual(r.multiDimArray[0, 1], 4);
334      Assert.AreEqual(r.multiDimArray[0, 2], 3);
335      Assert.AreEqual(r.multiDimArray[1, 0], 1);
336      Assert.AreEqual(r.multiDimArray[1, 1], 4);
337      Assert.AreEqual(r.multiDimArray[1, 2], 6);
338      Assert.IsFalse(r.boolean);
339      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
340      Assert.AreEqual(r.kvp.Key, "string key");
341      Assert.AreEqual(r.kvp.Value, 321);
342      Assert.IsNull(r.uninitialized);
343      Assert.AreEqual(newR.myEnum, TestEnum.va1);
344      Assert.AreEqual(newR.i[0], 7);
345      Assert.AreEqual(newR.i[1], 5);
346      Assert.AreEqual(newR.i[2], 6);
347      Assert.AreEqual(newR.s, "new value");
348      Assert.AreEqual(newR.intArray[0], 3);
349      Assert.AreEqual(newR.intArray[1], 2);
350      Assert.AreEqual(newR.intArray[2], 1);
351      Assert.AreEqual(newR.intList[0], 9);
352      Assert.AreEqual(newR.intList[1], 8);
353      Assert.AreEqual(newR.intList[2], 7);
354      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
355      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
356      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
357      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
358      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
359      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
360      Assert.AreEqual(newR.intStack.Pop(), 3);
361      Assert.AreEqual(newR.intStack.Pop(), 2);
362      Assert.AreEqual(newR.intStack.Pop(), 1);
363      Assert.IsFalse(newR.boolean);
364      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
365      Assert.AreEqual(newR.kvp.Key, "string key");
366      Assert.AreEqual(newR.kvp.Value, 321);
367      Assert.IsNull(newR.uninitialized);
368    }
369
370    private static Root InitializeComplexStorable() {
371      Root r = new Root();
372      r.intStack.Push(1);
373      r.intStack.Push(2);
374      r.intStack.Push(3);
375      r.selfReferences = new List<Root> { r, r };
376      r.c = new Custom { r = r };
377      r.dict.Add("one", 1);
378      r.dict.Add("two", 2);
379      r.dict.Add("three", 3);
380      r.myEnum = TestEnum.va1;
381      r.i = new[] { 7, 5, 6 };
382      r.s = "new value";
383      r.intArray = new ArrayList { 3, 2, 1 };
384      r.intList = new List<int> { 9, 8, 7 };
385      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
386      r.boolean = false;
387      r.dateTime = DateTime.Now;
388      r.kvp = new KeyValuePair<string, int>("string key", 321);
389      r.uninitialized = null;
390
391      return r;
392    }
393
394    [TestMethod]
395    [TestCategory("Persistence")]
396    [TestProperty("Time", "short")]
397    public void SelfReferences() {
398      C c = new C();
399      C[][] cs = new C[2][];
400      cs[0] = new C[] { c };
401      cs[1] = new C[] { c };
402      c.allCs = cs;
403      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
404      XmlGenerator.Serialize(cs, tempFile);
405      object o = XmlParser.Deserialize(tempFile);
406      Assert.AreEqual(
407        DebugStringGenerator.Serialize(cs),
408        DebugStringGenerator.Serialize(o));
409      Assert.AreSame(c, c.allCs[0][0]);
410      Assert.AreSame(c, c.allCs[1][0]);
411      Assert.AreSame(c, c.kvpList.Key[0]);
412      Assert.AreSame(c, c.kvpList.Value);
413      C[][] newCs = (C[][])o;
414      C newC = newCs[0][0];
415      Assert.AreSame(newC, newC.allCs[0][0]);
416      Assert.AreSame(newC, newC.allCs[1][0]);
417      Assert.AreSame(newC, newC.kvpList.Key[0]);
418      Assert.AreSame(newC, newC.kvpList.Value);
419    }
420
421    [TestMethod]
422    [TestCategory("Persistence")]
423    [TestProperty("Time", "short")]
424    public void ArrayCreation() {
425      ArrayList[] arrayListArray = new ArrayList[4];
426      arrayListArray[0] = new ArrayList();
427      arrayListArray[0].Add(arrayListArray);
428      arrayListArray[0].Add(arrayListArray);
429      arrayListArray[1] = new ArrayList();
430      arrayListArray[1].Add(arrayListArray);
431      arrayListArray[2] = new ArrayList();
432      arrayListArray[2].Add(arrayListArray);
433      arrayListArray[2].Add(arrayListArray);
434      Array a = Array.CreateInstance(
435                              typeof(object),
436                              new[] { 1, 2 }, new[] { 3, 4 });
437      arrayListArray[2].Add(a);
438      XmlGenerator.Serialize(arrayListArray, tempFile);
439      object o = XmlParser.Deserialize(tempFile);
440      Assert.AreEqual(
441        DebugStringGenerator.Serialize(arrayListArray),
442        DebugStringGenerator.Serialize(o));
443      ArrayList[] newArray = (ArrayList[])o;
444      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
445      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
446      Assert.AreSame(newArray, newArray[0][0]);
447      Assert.AreSame(newArray, newArray[2][1]);
448    }
449
450    [TestMethod]
451    [TestCategory("Persistence")]
452    [TestProperty("Time", "short")]
453    public void CustomSerializationProperty() {
454      Manager m = new Manager();
455      XmlGenerator.Serialize(m, tempFile);
456      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
457      Assert.AreNotEqual(
458        DebugStringGenerator.Serialize(m),
459        DebugStringGenerator.Serialize(newM));
460      Assert.AreEqual(m.dbl, newM.dbl);
461      Assert.AreEqual(m.lastLoadTime, new DateTime());
462      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
463      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
464    }
465
466    [TestMethod]
467    [TestCategory("Persistence")]
468    [TestProperty("Time", "short")]
469    public void Primitives() {
470      PrimitivesTest sdt = new PrimitivesTest();
471      XmlGenerator.Serialize(sdt, tempFile);
472      object o = XmlParser.Deserialize(tempFile);
473      Assert.AreEqual(
474        DebugStringGenerator.Serialize(sdt),
475        DebugStringGenerator.Serialize(o));
476    }
477
478    [TestMethod]
479    [TestCategory("Persistence")]
480    [TestProperty("Time", "short")]
481    public void MultiDimensionalArray() {
482      string[,] mDimString = new string[,] {
483        {"ora", "et", "labora"},
484        {"Beten", "und", "Arbeiten"}
485      };
486      XmlGenerator.Serialize(mDimString, tempFile);
487      object o = XmlParser.Deserialize(tempFile);
488      Assert.AreEqual(
489        DebugStringGenerator.Serialize(mDimString),
490        DebugStringGenerator.Serialize(o));
491    }
492
493    [StorableType("f4af4d3d-7ae6-4da5-ab3c-5df3ca2daca7")]
494    public class NestedType {
495      [Storable]
496      private string value = "value";
497      public override bool Equals(object obj) {
498        NestedType nt = obj as NestedType;
499        if (nt == null)
500          throw new NotSupportedException();
501        return nt.value == value;
502      }
503      public override int GetHashCode() {
504        return value.GetHashCode();
505      }
506    }
507
508    [TestMethod]
509    [TestCategory("Persistence")]
510    [TestProperty("Time", "short")]
511    public void NestedTypeTest() {
512      NestedType t = new NestedType();
513      XmlGenerator.Serialize(t, tempFile);
514      object o = XmlParser.Deserialize(tempFile);
515      Assert.AreEqual(
516        DebugStringGenerator.Serialize(t),
517        DebugStringGenerator.Serialize(o));
518      Assert.IsTrue(t.Equals(o));
519    }
520
521
522    [TestMethod]
523    [TestCategory("Persistence")]
524    [TestProperty("Time", "short")]
525    public void SimpleArray() {
526      string[] strings = { "ora", "et", "labora" };
527      XmlGenerator.Serialize(strings, tempFile);
528      object o = XmlParser.Deserialize(tempFile);
529      Assert.AreEqual(
530        DebugStringGenerator.Serialize(strings),
531        DebugStringGenerator.Serialize(o));
532    }
533
534    [TestMethod]
535    [TestCategory("Persistence")]
536    [TestProperty("Time", "short")]
537    public void PrimitiveRoot() {
538      XmlGenerator.Serialize(12.3f, tempFile);
539      object o = XmlParser.Deserialize(tempFile);
540      Assert.AreEqual(
541        DebugStringGenerator.Serialize(12.3f),
542        DebugStringGenerator.Serialize(o));
543    }
544
545    private string formatFullMemberName(MemberInfo mi) {
546      return new StringBuilder()
547        .Append(mi.DeclaringType.Assembly.GetName().Name)
548        .Append(": ")
549        .Append(mi.DeclaringType.Namespace)
550        .Append('.')
551        .Append(mi.DeclaringType.Name)
552        .Append('.')
553        .Append(mi.Name).ToString();
554    }
555
556    public void CodingConventions() {
557      List<string> lowerCaseMethodNames = new List<string>();
558      List<string> lowerCaseProperties = new List<string>();
559      List<string> lowerCaseFields = new List<string>();
560      foreach (Assembly a in PluginLoader.Assemblies) {
561        if (!a.GetName().Name.StartsWith("HeuristicLab"))
562          continue;
563        foreach (Type t in a.GetTypes()) {
564          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
565            if (mi.DeclaringType.Name.StartsWith("<>"))
566              continue;
567            if (char.IsLower(mi.Name[0])) {
568              if (mi.MemberType == MemberTypes.Field)
569                lowerCaseFields.Add(formatFullMemberName(mi));
570              if (mi.MemberType == MemberTypes.Property)
571                lowerCaseProperties.Add(formatFullMemberName(mi));
572              if (mi.MemberType == MemberTypes.Method &&
573                !mi.Name.StartsWith("get_") &&
574                !mi.Name.StartsWith("set_") &&
575                !mi.Name.StartsWith("add_") &&
576                !mi.Name.StartsWith("remove_") &&
577                !mi.Name.StartsWith("op_"))
578                lowerCaseMethodNames.Add(formatFullMemberName(mi));
579            }
580          }
581        }
582      }
583      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
584      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
585      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
586    }
587
588    [TestMethod]
589    [TestCategory("Persistence")]
590    [TestProperty("Time", "short")]
591    public void Number2StringDecomposer() {
592      NumberTest sdt = new NumberTest();
593      XmlGenerator.Serialize(sdt, tempFile,
594        new Configuration(new XmlFormat(),
595          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
596          new List<ICompositeSerializer> {
597            new StorableSerializer(),
598            new Number2StringSerializer() }));
599      object o = XmlParser.Deserialize(tempFile);
600      Assert.AreEqual(
601        DebugStringGenerator.Serialize(sdt),
602        DebugStringGenerator.Serialize(o));
603      Assert.IsTrue(sdt.Equals(o));
604    }
605
606    [TestMethod]
607    [TestCategory("Persistence")]
608    [TestProperty("Time", "short")]
609    public void Enums() {
610      EnumTest et = new EnumTest();
611      et.simpleEnum = SimpleEnum.two;
612      et.complexEnum = ComplexEnum.three;
613      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
614      XmlGenerator.Serialize(et, tempFile);
615      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
616      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
617      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
618      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
619    }
620
621    [TestMethod]
622    [TestCategory("Persistence")]
623    [TestProperty("Time", "short")]
624    public void TestAliasingWithOverriddenEquals() {
625      List<IntWrapper> ints = new List<IntWrapper>();
626      ints.Add(new IntWrapper(1));
627      ints.Add(new IntWrapper(1));
628      Assert.AreEqual(ints[0], ints[1]);
629      Assert.AreNotSame(ints[0], ints[1]);
630      XmlGenerator.Serialize(ints, tempFile);
631      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
632      Assert.AreEqual(newInts[0].Value, 1);
633      Assert.AreEqual(newInts[1].Value, 1);
634      Assert.AreEqual(newInts[0], newInts[1]);
635      Assert.AreNotSame(newInts[0], newInts[1]);
636    }
637
638    [TestMethod]
639    [TestCategory("Persistence")]
640    [TestProperty("Time", "short")]
641    public void NonDefaultConstructorTest() {
642      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
643      try {
644        XmlGenerator.Serialize(c, tempFile);
645        Assert.Fail("Exception not thrown");
646      } catch (PersistenceException) {
647      }
648    }
649
650    [TestMethod]
651    [TestCategory("Persistence")]
652    [TestProperty("Time", "short")]
653    public void TestSavingException() {
654      List<int> list = new List<int> { 1, 2, 3 };
655      XmlGenerator.Serialize(list, tempFile);
656      NonSerializable s = new NonSerializable();
657      try {
658        XmlGenerator.Serialize(s, tempFile);
659        Assert.Fail("Exception expected");
660      } catch (PersistenceException) { }
661      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
662      Assert.AreEqual(list[0], newList[0]);
663      Assert.AreEqual(list[1], newList[1]);
664    }
665
666    [TestMethod]
667    [TestCategory("Persistence")]
668    [TestProperty("Time", "short")]
669    public void TestTypeStringConversion() {
670      string name = typeof(List<int>[]).AssemblyQualifiedName;
671      string shortName =
672        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
673      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
674      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
675      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
676    }
677
678    [TestMethod]
679    [TestCategory("Persistence")]
680    [TestProperty("Time", "short")]
681    public void TestHexadecimalPublicKeyToken() {
682      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
683      string shortName = "TestClass, TestAssembly";
684      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
685      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
686    }
687
688    [TestMethod]
689    [TestCategory("Persistence")]
690    [TestProperty("Time", "short")]
691    public void TestMultipleFailure() {
692      List<NonSerializable> l = new List<NonSerializable>();
693      l.Add(new NonSerializable());
694      l.Add(new NonSerializable());
695      l.Add(new NonSerializable());
696      try {
697        var s = new HeuristicLab.Persistence.Core.Serializer(l,
698          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
699          "ROOT", true);
700        StringBuilder tokens = new StringBuilder();
701        foreach (var token in s) {
702          tokens.Append(token.ToString());
703        }
704        Assert.Fail("Exception expected");
705      } catch (PersistenceException px) {
706        Assert.AreEqual(3, px.Data.Count);
707      }
708    }
709
710    [TestMethod]
711    [TestCategory("Persistence")]
712    [TestProperty("Time", "short")]
713    public void TestAssemblyVersionCheck() {
714      IntWrapper i = new IntWrapper(1);
715      var s = new HeuristicLab.Persistence.Core.Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
716      XmlGenerator g = new XmlGenerator();
717      StringBuilder dataString = new StringBuilder();
718      foreach (var token in s) {
719        dataString.Append(g.Format(token));
720      }
721      StringBuilder typeString = new StringBuilder();
722      foreach (var line in g.Format(s.TypeCache))
723        typeString.Append(line);
724      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
725      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
726      IntWrapper newI = (IntWrapper)d.Deserialize(p);
727      Assert.AreEqual(i.Value, newI.Value);
728
729      string newTypeString = Regex.Replace(typeString.ToString(),
730        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
731        "Version=0.0.9999.9999");
732      try {
733        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
734        Assert.Fail("Exception expected");
735      } catch (PersistenceException x) {
736        Assert.IsTrue(x.Message.Contains("incompatible"));
737      }
738      newTypeString = Regex.Replace(typeString.ToString(),
739        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
740        "Version=$1.9999.9999");
741      try {
742        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
743        Assert.Fail("Exception expected");
744      } catch (PersistenceException x) {
745        Assert.IsTrue(x.Message.Contains("newer"));
746      }
747    }
748
749    [TestMethod]
750    [TestCategory("Persistence")]
751    [TestProperty("Time", "short")]
752    public void InheritanceTest() {
753      New n = new New();
754      XmlGenerator.Serialize(n, tempFile);
755      New nn = (New)XmlParser.Deserialize(tempFile);
756      Assert.AreEqual(n.Name, nn.Name);
757      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
758    }
759
760    [StorableType("121169c6-b68a-491b-93e7-9925d508c0f3")]
761    class Child {
762      [Storable]
763      public GrandParent grandParent;
764    }
765
766    [StorableType("58a160dd-1851-4f78-b585-cdd05d4213f2")]
767    class Parent {
768      [Storable]
769      public Child child;
770    }
771
772    [StorableType("f99dbc0d-6f4c-4165-8d94-fb749f8cee33")]
773    class GrandParent {
774      [Storable]
775      public Parent parent;
776    }
777
778    [TestMethod]
779    [TestCategory("Persistence")]
780    [TestProperty("Time", "short")]
781    public void InstantiateParentChainReference() {
782      GrandParent gp = new GrandParent();
783      gp.parent = new Parent();
784      gp.parent.child = new Child();
785      gp.parent.child.grandParent = gp;
786      Assert.AreSame(gp, gp.parent.child.grandParent);
787      XmlGenerator.Serialize(gp, tempFile);
788      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
789      Assert.AreSame(newGp, newGp.parent.child.grandParent);
790    }
791
792    [StorableType("d4898d57-d578-4136-86f6-c8f615dbb4ab")]
793    struct TestStruct {
794      int value;
795      int PropertyValue { get; set; }
796      public TestStruct(int value)
797        : this() {
798        this.value = value;
799        PropertyValue = value;
800      }
801    }
802
803    [TestMethod]
804    [TestCategory("Persistence")]
805    [TestProperty("Time", "short")]
806    public void StructTest() {
807      TestStruct s = new TestStruct(10);
808      XmlGenerator.Serialize(s, tempFile);
809      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
810      Assert.AreEqual(s, newS);
811    }
812
813    [TestMethod]
814    [TestCategory("Persistence")]
815    [TestProperty("Time", "short")]
816    public void PointTest() {
817      Point p = new Point(12, 34);
818      XmlGenerator.Serialize(p, tempFile);
819      Point newP = (Point)XmlParser.Deserialize(tempFile);
820      Assert.AreEqual(p, newP);
821    }
822
823    [TestMethod]
824    [TestCategory("Persistence")]
825    [TestProperty("Time", "short")]
826    public void NullableValueTypes() {
827      double?[] d = new double?[] { null, 1, 2, 3 };
828      XmlGenerator.Serialize(d, tempFile);
829      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
830      Assert.AreEqual(d[0], newD[0]);
831      Assert.AreEqual(d[1], newD[1]);
832      Assert.AreEqual(d[2], newD[2]);
833      Assert.AreEqual(d[3], newD[3]);
834    }
835
836    [TestMethod]
837    [TestCategory("Persistence")]
838    [TestProperty("Time", "short")]
839    public void BitmapTest() {
840      Icon icon = System.Drawing.SystemIcons.Hand;
841      Bitmap bitmap = icon.ToBitmap();
842      XmlGenerator.Serialize(bitmap, tempFile);
843      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
844
845      Assert.AreEqual(bitmap.Size, newBitmap.Size);
846      for (int i = 0; i < bitmap.Size.Width; i++)
847        for (int j = 0; j < bitmap.Size.Height; j++)
848          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
849    }
850
851    [StorableType("2a354c02-5268-41d1-b80f-c68f1d9c2337")]
852    private class PersistenceHooks {
853      [Storable]
854      public int a;
855      [Storable]
856      public int b;
857      public int sum;
858      public bool WasSerialized { get; private set; }
859      [StorableHook(HookType.BeforeSerialization)]
860      void PreSerializationHook() {
861        WasSerialized = true;
862      }
863      [StorableHook(HookType.AfterDeserialization)]
864      void PostDeserializationHook() {
865        sum = a + b;
866      }
867    }
868
869    [TestMethod]
870    [TestCategory("Persistence")]
871    [TestProperty("Time", "short")]
872    public void HookTest() {
873      PersistenceHooks hookTest = new PersistenceHooks();
874      hookTest.a = 2;
875      hookTest.b = 5;
876      Assert.IsFalse(hookTest.WasSerialized);
877      Assert.AreEqual(hookTest.sum, 0);
878      XmlGenerator.Serialize(hookTest, tempFile);
879      Assert.IsTrue(hookTest.WasSerialized);
880      Assert.AreEqual(hookTest.sum, 0);
881      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
882      Assert.AreEqual(newHookTest.a, hookTest.a);
883      Assert.AreEqual(newHookTest.b, hookTest.b);
884      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
885      Assert.IsFalse(newHookTest.WasSerialized);
886    }
887
888    [StorableType("fd155497-a299-413e-a251-220f9d21c92e")]
889    private class CustomConstructor {
890      public string Value = "none";
891      public CustomConstructor() {
892        Value = "default";
893      }
894      [StorableConstructor]
895      private CustomConstructor(StorableConstructorFlag deserializing) {
896        Value = "persistence";
897      }
898    }
899
900    [TestMethod]
901    [TestCategory("Persistence")]
902    [TestProperty("Time", "short")]
903    public void TestCustomConstructor() {
904      CustomConstructor cc = new CustomConstructor();
905      Assert.AreEqual(cc.Value, "default");
906      XmlGenerator.Serialize(cc, tempFile);
907      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
908      Assert.AreEqual(newCC.Value, "persistence");
909    }
910
911    [StorableType("f6cbcbdd-a3a1-4a87-b2e4-413f0255b12a")]
912    public class ExplodingDefaultConstructor {
913      public ExplodingDefaultConstructor() {
914        throw new Exception("this constructor will always fail");
915      }
916      public ExplodingDefaultConstructor(string password) {
917      }
918    }
919
920    [TestMethod]
921    [TestCategory("Persistence")]
922    [TestProperty("Time", "short")]
923    public void TestConstructorExceptionUnwrapping() {
924      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
925      XmlGenerator.Serialize(x, tempFile);
926      try {
927        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
928        Assert.Fail("Exception expected");
929      } catch (PersistenceException pe) {
930        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
931      }
932    }
933
934    [TestMethod]
935    [TestCategory("Persistence")]
936    [TestProperty("Time", "short")]
937    public void TestRejectionJustifications() {
938      NonSerializable ns = new NonSerializable();
939      try {
940        XmlGenerator.Serialize(ns, tempFile);
941        Assert.Fail("PersistenceException expected");
942      } catch (PersistenceException x) {
943        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
944      }
945    }
946
947    [TestMethod]
948    [TestCategory("Persistence")]
949    [TestProperty("Time", "short")]
950    public void TestStreaming() {
951      using (MemoryStream stream = new MemoryStream()) {
952        Root r = InitializeComplexStorable();
953        XmlGenerator.Serialize(r, stream);
954        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
955          Root newR = (Root)XmlParser.Deserialize(stream2);
956          CompareComplexStorables(r, newR);
957        }
958      }
959    }
960
961    [StorableType("7333a419-f549-4f88-a761-a1197cf90bce")]
962    public class HookInheritanceTestBase {
963      [Storable]
964      public object a;
965      public object link;
966      [StorableHook(HookType.AfterDeserialization)]
967      private void relink() {
968        link = a;
969      }
970    }
971
972    [StorableType("d05112d0-57db-43fc-86b2-a4da9d6cb84b")]
973    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
974      [Storable]
975      public object b;
976      [StorableHook(HookType.AfterDeserialization)]
977      private void relink() {
978        Assert.AreSame(a, link);
979        link = b;
980      }
981    }
982
983    [TestMethod]
984    [TestCategory("Persistence")]
985    [TestProperty("Time", "short")]
986    public void TestLinkInheritance() {
987      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
988      c.a = new object();
989      XmlGenerator.Serialize(c, tempFile);
990      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
991      Assert.AreSame(c.b, c.link);
992    }
993
994    [StorableType(StorableMemberSelection.AllFields, "6f92b947-032a-4455-81e6-116bf4c31f92")]
995    public class AllFieldsStorable {
996      public int Value1 = 1;
997      [Storable]
998      public int Value2 = 2;
999      public int Value3 { get; private set; }
1000      public int Value4 { get; private set; }
1001      [StorableConstructor]
1002      public AllFieldsStorable(bool isDeserializing) {
1003        if (!isDeserializing) {
1004          Value1 = 12;
1005          Value2 = 23;
1006          Value3 = 34;
1007          Value4 = 56;
1008        }
1009      }
1010    }
1011
1012    [TestMethod]
1013    [TestCategory("Persistence")]
1014    [TestProperty("Time", "short")]
1015    public void TestStorableClassDiscoveryAllFields() {
1016      AllFieldsStorable afs = new AllFieldsStorable(false);
1017      XmlGenerator.Serialize(afs, tempFile);
1018      AllFieldsStorable newAfs = (AllFieldsStorable)XmlParser.Deserialize(tempFile);
1019      Assert.AreEqual(afs.Value1, newAfs.Value1);
1020      Assert.AreEqual(afs.Value2, newAfs.Value2);
1021      Assert.AreEqual(0, newAfs.Value3);
1022      Assert.AreEqual(0, newAfs.Value4);
1023    }
1024
1025    [StorableType(StorableMemberSelection.AllProperties, "9e5eff24-617e-44bc-ae0f-258bfd804247")]
1026    public class AllPropertiesStorable {
1027      public int Value1 = 1;
1028      [Storable]
1029      public int Value2 = 2;
1030      public int Value3 { get; private set; }
1031      public int Value4 { get; private set; }
1032
1033      [StorableConstructor]
1034      public AllPropertiesStorable(bool isDeserializing) {
1035        if (!isDeserializing) {
1036          Value1 = 12;
1037          Value2 = 23;
1038          Value3 = 34;
1039          Value4 = 56;
1040        }
1041      }
1042    }
1043
1044    [TestMethod]
1045    [TestCategory("Persistence")]
1046    [TestProperty("Time", "short")]
1047    public void TestStorableClassDiscoveryAllProperties() {
1048      AllPropertiesStorable afs = new AllPropertiesStorable(false);
1049      XmlGenerator.Serialize(afs, tempFile);
1050      AllPropertiesStorable newAfs = (AllPropertiesStorable)XmlParser.Deserialize(tempFile);
1051      Assert.AreEqual(1, newAfs.Value1);
1052      Assert.AreEqual(2, newAfs.Value2);
1053      Assert.AreEqual(afs.Value3, newAfs.Value3);
1054      Assert.AreEqual(afs.Value4, newAfs.Value4);
1055
1056    }
1057
1058    [StorableType(StorableMemberSelection.AllFieldsAndAllProperties, "b6e3468d-5aaf-47d9-bd87-6931b2c705cd")]
1059    public class AllFieldsAndAllPropertiesStorable {
1060      public int Value1 = 1;
1061      [Storable]
1062      public int Value2 = 2;
1063      public int Value3 { get; private set; }
1064      public int Value4 { get; private set; }
1065      [StorableConstructor]
1066      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1067        if (!isDeserializing) {
1068          Value1 = 12;
1069          Value2 = 23;
1070          Value3 = 34;
1071          Value4 = 56;
1072        }
1073      }
1074    }
1075
1076    [TestMethod]
1077    [TestCategory("Persistence")]
1078    [TestProperty("Time", "short")]
1079    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1080      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1081      XmlGenerator.Serialize(afs, tempFile);
1082      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)XmlParser.Deserialize(tempFile);
1083      Assert.AreEqual(afs.Value1, newAfs.Value1);
1084      Assert.AreEqual(afs.Value2, newAfs.Value2);
1085      Assert.AreEqual(afs.Value3, newAfs.Value3);
1086      Assert.AreEqual(afs.Value4, newAfs.Value4);
1087    }
1088
1089    [StorableType(StorableMemberSelection.MarkedOnly, "1730eaa1-0507-4e08-94d8-64e213f3401d")]
1090    public class MarkedOnlyStorable {
1091      public int Value1 = 1;
1092      [Storable]
1093      public int Value2 = 2;
1094      public int Value3 { get; private set; }
1095      public int Value4 { get; private set; }
1096      [StorableConstructor]
1097      public MarkedOnlyStorable(bool isDeserializing) {
1098        if (!isDeserializing) {
1099          Value1 = 12;
1100          Value2 = 23;
1101          Value3 = 34;
1102          Value4 = 56;
1103        }
1104      }
1105    }
1106
1107    [TestMethod]
1108    [TestCategory("Persistence")]
1109    [TestProperty("Time", "short")]
1110    public void TestStorableClassDiscoveryMarkedOnly() {
1111      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1112      XmlGenerator.Serialize(afs, tempFile);
1113      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
1114      Assert.AreEqual(1, newAfs.Value1);
1115      Assert.AreEqual(afs.Value2, newAfs.Value2);
1116      Assert.AreEqual(0, newAfs.Value3);
1117      Assert.AreEqual(0, newAfs.Value4);
1118    }
1119
1120    [TestMethod]
1121    [TestCategory("Persistence")]
1122    [TestProperty("Time", "short")]
1123    public void TestLineEndings() {
1124      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1125      List<string> lines = new List<string>();
1126      foreach (var br in lineBreaks)
1127        lines.Add("line1" + br + "line2");
1128      XmlGenerator.Serialize(lines, tempFile);
1129      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
1130      Assert.AreEqual(lines.Count, newLines.Count);
1131      for (int i = 0; i < lineBreaks.Count; i++) {
1132        Assert.AreEqual(lines[i], newLines[i]);
1133      }
1134    }
1135
1136    [TestMethod]
1137    [TestCategory("Persistence")]
1138    [TestProperty("Time", "short")]
1139    public void TestSpecialNumbers() {
1140      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1141      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1142      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1143      Assert.IsTrue(double.IsNaN(specials[2]));
1144      XmlGenerator.Serialize(specials, tempFile);
1145      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
1146      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1147      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1148      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1149    }
1150
1151    [TestMethod]
1152    [TestCategory("Persistence")]
1153    [TestProperty("Time", "short")]
1154    public void TestStringSplit() {
1155      string s = "1.2;2.3;3.4;;;4.9";
1156      var l = s.EnumerateSplit(';').ToList();
1157      Assert.AreEqual("1.2", l[0]);
1158      Assert.AreEqual("2.3", l[1]);
1159      Assert.AreEqual("3.4", l[2]);
1160      Assert.AreEqual("4.9", l[3]);
1161    }
1162
1163    [TestMethod]
1164    [TestCategory("Persistence")]
1165    [TestProperty("Time", "medium")]
1166    public void TestCompactNumberArraySerializer() {
1167      System.Random r = new System.Random();
1168      double[] a = new double[CompactNumberArray2StringSerializer.SPLIT_THRESHOLD * 2 + 1];
1169      for (int i = 0; i < a.Length; i++)
1170        a[i] = r.Next(10);
1171      var config = ConfigurationService.Instance.GetDefaultConfig(new XmlFormat());
1172      config = new Configuration(config.Format,
1173        config.PrimitiveSerializers.Where(s => s.SourceType != typeof(double[])),
1174        config.CompositeSerializers);
1175      XmlGenerator.Serialize(a, tempFile, config);
1176      double[] newA = XmlParser.Deserialize<double[]>(tempFile);
1177      Assert.AreEqual(a.Length, newA.Length);
1178      for (int i = 0; i < a.Rank; i++) {
1179        Assert.AreEqual(a.GetLength(i), newA.GetLength(i));
1180        Assert.AreEqual(a.GetLowerBound(i), newA.GetLowerBound(i));
1181      }
1182      for (int i = 0; i < a.Length; i++) {
1183        Assert.AreEqual(a[i], newA[i]);
1184      }
1185    }
1186    [StorableType("57867b53-fafd-4c4f-aa15-dcfd87fbffe7")]
1187    private class IdentityComparer<T> : IEqualityComparer<T> {
1188
1189      public bool Equals(T x, T y) {
1190        return x.Equals(y);
1191      }
1192
1193      public int GetHashCode(T obj) {
1194        return obj.GetHashCode();
1195      }
1196    }
1197
1198    [TestMethod]
1199    [TestCategory("Persistence")]
1200    [TestProperty("Time", "short")]
1201    public void TestHashSetSerializer() {
1202      var hashSets = new List<HashSet<int>>() {
1203        new HashSet<int>(new[] { 1, 2, 3 }),
1204        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1205      };
1206      XmlGenerator.Serialize(hashSets, tempFile);
1207      var newHashSets = XmlParser.Deserialize<List<HashSet<int>>>(tempFile);
1208      Assert.IsTrue(newHashSets[0].Contains(1));
1209      Assert.IsTrue(newHashSets[0].Contains(2));
1210      Assert.IsTrue(newHashSets[0].Contains(3));
1211      Assert.IsTrue(newHashSets[1].Contains(4));
1212      Assert.IsTrue(newHashSets[1].Contains(5));
1213      Assert.IsTrue(newHashSets[1].Contains(6));
1214      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1215      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1216    }
1217
1218    [TestMethod]
1219    [TestCategory("Persistence")]
1220    [TestProperty("Time", "short")]
1221    public void TestConcreteDictionarySerializer() {
1222      var dictionaries = new List<Dictionary<int, int>>() {
1223        new Dictionary<int, int>(),
1224        new Dictionary<int, int>(new IdentityComparer<int>()),
1225      };
1226      dictionaries[0].Add(1, 1);
1227      dictionaries[0].Add(2, 2);
1228      dictionaries[0].Add(3, 3);
1229      dictionaries[1].Add(4, 4);
1230      dictionaries[1].Add(5, 5);
1231      dictionaries[1].Add(6, 6);
1232      XmlGenerator.Serialize(dictionaries, tempFile, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1233      var newDictionaries = XmlParser.Deserialize<List<Dictionary<int, int>>>(tempFile);
1234      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1235      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1236      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1237      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1238      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1239      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1240      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1241      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1242      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1243      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1244      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1245      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1246      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1247      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1248    }
1249
1250    [StorableType("aa595fbc-7359-49ad-a274-204ff3c97bb4")]
1251    public class ReadOnlyFail {
1252      [Storable]
1253      public string ReadOnly {
1254        get { return "fail"; }
1255      }
1256    }
1257
1258    [TestMethod]
1259    [TestCategory("Persistence")]
1260    [TestProperty("Time", "short")]
1261    public void TestReadOnlyFail() {
1262      try {
1263        XmlGenerator.Serialize(new ReadOnlyFail(), tempFile);
1264        Assert.Fail("Exception expected");
1265      } catch (PersistenceException) {
1266      } catch {
1267        Assert.Fail("PersistenceException expected");
1268      }
1269    }
1270
1271
1272    [StorableType("34008801-bb73-4810-ad1a-de9921b49a5d")]
1273    public class WriteOnlyFail {
1274      [Storable]
1275      public string WriteOnly {
1276        set { throw new InvalidOperationException("this property should never be set."); }
1277      }
1278    }
1279
1280    [TestMethod]
1281    [TestCategory("Persistence")]
1282    [TestProperty("Time", "short")]
1283    public void TestWriteOnlyFail() {
1284      try {
1285        XmlGenerator.Serialize(new WriteOnlyFail(), tempFile);
1286        Assert.Fail("Exception expected");
1287      } catch (PersistenceException) {
1288      } catch {
1289        Assert.Fail("PersistenceException expected.");
1290      }
1291    }
1292
1293    [StorableType("38575b53-c706-4d20-a255-c567c21c99a4")]
1294    public class OneWayTest {
1295      public OneWayTest() { this.value = "default"; }
1296      public string value;
1297      [Storable(AllowOneWay = true)]
1298      public string ReadOnly {
1299        get { return "ReadOnly"; }
1300      }
1301      [Storable(AllowOneWay = true)]
1302      public string WriteOnly {
1303        set { this.value = value; }
1304      }
1305    }
1306
1307    [TestMethod]
1308    [TestCategory("Persistence")]
1309    [TestProperty("Time", "short")]
1310    public void TestOneWaySerialization() {
1311      var test = new OneWayTest();
1312      var serializer = new HeuristicLab.Persistence.Core.Serializer(test, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1313      var it = serializer.GetEnumerator();
1314      it.MoveNext();
1315      Assert.AreEqual("ROOT", ((BeginToken)it.Current).Name); it.MoveNext();
1316      Assert.AreEqual("ReadOnly", ((PrimitiveToken)it.Current).Name); it.MoveNext();
1317      Assert.AreEqual("ROOT", ((EndToken)it.Current).Name); it.MoveNext();
1318      var deserializer = new Deserializer(new[] {
1319        new TypeMapping(0, typeof(OneWayTest).AssemblyQualifiedName, typeof(StorableSerializer).AssemblyQualifiedName),
1320        new TypeMapping(1, typeof(string).AssemblyQualifiedName, typeof(String2XmlSerializer).AssemblyQualifiedName) });
1321      var newTest = (OneWayTest)deserializer.Deserialize(new ISerializationToken[] {
1322        new BeginToken("ROOT", 0, 0),
1323        new PrimitiveToken("WriteOnly", 1, 1, new XmlString("<![CDATA[serial data]]>")),
1324        new EndToken("ROOT", 0, 0)
1325      });
1326      Assert.AreEqual("serial data", newTest.value);
1327    }
1328
1329    [TestMethod]
1330    [TestCategory("Persistence")]
1331    [TestProperty("Time", "short")]
1332    public void TestTypeCacheExport() {
1333      var test = new List<List<int>>();
1334      test.Add(new List<int>() { 1, 2, 3 });
1335      IEnumerable<Type> types;
1336      using (var stream = new MemoryStream()) {
1337        XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1338      }
1339      List<Type> t = new List<Type>(types);
1340      // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1341      Assert.IsTrue(t.Contains(typeof(List<int>)));
1342      Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1343      Assert.AreEqual(t.Count, 2);
1344    }
1345
1346    [TestMethod]
1347    [TestCategory("Persistence")]
1348    [TestProperty("Time", "short")]
1349    public void TupleTest() {
1350      var t1 = Tuple.Create(1);
1351      var t2 = Tuple.Create('1', "2");
1352      var t3 = Tuple.Create(3.0, 3f, 5);
1353      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1354      var tuple = Tuple.Create(t1, t2, t3, t4);
1355      XmlGenerator.Serialize(tuple, tempFile);
1356      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);
1357      Assert.AreEqual(tuple, newTuple);
1358    }
1359
1360    [TestMethod]
1361    [TestCategory("Persistence")]
1362    [TestProperty("Time", "short")]
1363    public void FontTest() {
1364      List<Font> fonts = new List<Font>() {
1365        new Font(FontFamily.GenericSansSerif, 12),
1366        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1367        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1368        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1369      };
1370      XmlGenerator.Serialize(fonts, tempFile);
1371      var newFonts = XmlParser.Deserialize<List<Font>>(tempFile);
1372      Assert.AreEqual(fonts[0], newFonts[0]);
1373      Assert.AreEqual(fonts[1], newFonts[1]);
1374      Assert.AreEqual(fonts[2], newFonts[2]);
1375      Assert.AreEqual(fonts[3], newFonts[3]);
1376    }
1377
1378    [TestMethod]
1379    [TestCategory("Persistence")]
1380    [TestProperty("Time", "medium")]
1381    public void ConcurrencyTest() {
1382      int n = 20;
1383      Task[] tasks = new Task[n];
1384      for (int i = 0; i < n; i++) {
1385        tasks[i] = Task.Factory.StartNew((idx) => {
1386          byte[] data;
1387          using (var stream = new MemoryStream()) {
1388            XmlGenerator.Serialize(new GeneticAlgorithm(), stream);
1389            data = stream.ToArray();
1390          }
1391        }, i);
1392      }
1393      Task.WaitAll(tasks);
1394    }
1395
1396    [TestMethod]
1397    [TestCategory("Persistence")]
1398    [TestProperty("Time", "medium")]
1399    public void ConcurrentBitmapTest() {
1400      Bitmap b = new Bitmap(300, 300);
1401      System.Random r = new System.Random();
1402      for (int x = 0; x < b.Height; x++) {
1403        for (int y = 0; y < b.Width; y++) {
1404          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1405        }
1406      }
1407      Task[] tasks = new Task[20];
1408      byte[][] datas = new byte[tasks.Length][];
1409      for (int i = 0; i < tasks.Length; i++) {
1410        tasks[i] = Task.Factory.StartNew((idx) => {
1411          using (var stream = new MemoryStream()) {
1412            XmlGenerator.Serialize(b, stream);
1413            datas[(int)idx] = stream.ToArray();
1414          }
1415        }, i);
1416      }
1417      Task.WaitAll(tasks);
1418    }
1419
1420    [StorableType("07c965fc-8bd3-4baf-967c-374e1e9d9b31")]
1421    public class G<T, T2> {
1422      [StorableType("f9b10931-841f-4e93-b5d7-3d025a9bf998")]
1423      public class S { }
1424      [StorableType("a9414e79-427a-4dd2-a231-832314c834e3")]
1425      public class S2<T3, T4> { }
1426    }
1427
1428    [TestMethod]
1429    [TestCategory("Persistence")]
1430    [TestProperty("Time", "short")]
1431    public void TestInternalClassOfGeneric() {
1432      var s = new G<int, char>.S();
1433      var typeName = s.GetType().AssemblyQualifiedName;
1434      Assert.AreEqual(
1435        "UseCases.G<Int32,Char>.S",
1436        TypeNameParser.Parse(typeName).GetTypeNameInCode(false));
1437      XmlGenerator.Serialize(s, tempFile);
1438      var s1 = XmlParser.Deserialize(tempFile);
1439    }
1440
1441    [TestMethod]
1442    [TestCategory("Persistence")]
1443    [TestProperty("Time", "short")]
1444    public void TestInternalClassOfGeneric2() {
1445      var s = new G<int, float>.S2<int, char>();
1446      var typeName = s.GetType().AssemblyQualifiedName;
1447      Assert.AreEqual(
1448        "UseCases.G<Int32,Single>.S2<Int32,Char>",
1449        TypeNameParser.Parse(typeName).GetTypeNameInCode(false));
1450      XmlGenerator.Serialize(s, tempFile);
1451      var s1 = XmlParser.Deserialize(tempFile);
1452    }
1453
1454    [TestMethod]
1455    [TestCategory("Persistence")]
1456    [TestProperty("Time", "short")]
1457    public void TestSpecialCharacters() {
1458      var s = "abc" + "\x15" + "def";
1459      XmlGenerator.Serialize(s, tempFile);
1460      var newS = XmlParser.Deserialize(tempFile);
1461      Assert.AreEqual(s, newS);
1462    }
1463
1464    [TestMethod]
1465    [TestCategory("Persistence")]
1466    [TestProperty("Time", "short")]
1467    public void TestByteArray() {
1468      var b = new byte[3];
1469      b[0] = 0;
1470      b[1] = 200;
1471      b[2] = byte.MaxValue;
1472      XmlGenerator.Serialize(b, tempFile);
1473      var newB = (byte[])XmlParser.Deserialize(tempFile);
1474      CollectionAssert.AreEqual(b, newB);
1475    }
1476
1477    [TestMethod]
1478    [TestCategory("Persistence")]
1479    [TestProperty("Time", "short")]
1480    public void TestOptionalNumberEnumerable() {
1481      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
1482      XmlGenerator.Serialize(values, tempFile);
1483      var newValues = (List<double?>)XmlParser.Deserialize(tempFile);
1484      CollectionAssert.AreEqual(values, newValues);
1485    }
1486
1487    [TestMethod]
1488    [TestCategory("Persistence")]
1489    [TestProperty("Time", "short")]
1490    public void TestOptionalDateTimeEnumerable() {
1491      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
1492        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
1493      XmlGenerator.Serialize(values, tempFile);
1494      var newValues = (List<DateTime?>)XmlParser.Deserialize(tempFile);
1495      CollectionAssert.AreEqual(values, newValues);
1496    }
1497
1498    [TestMethod]
1499    [TestCategory("Persistence")]
1500    [TestProperty("Time", "short")]
1501    public void TestStringEnumerable() {
1502      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
1503      XmlGenerator.Serialize(values, tempFile);
1504      var newValues = (List<String>)XmlParser.Deserialize(tempFile);
1505      CollectionAssert.AreEqual(values, newValues);
1506    }
1507
1508    [TestMethod]
1509    [TestCategory("Persistence")]
1510    [TestProperty("Time", "short")]
1511    public void TestUnicodeCharArray() {
1512      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1513      XmlGenerator.Serialize(s, tempFile);
1514      var newS = (char[])XmlParser.Deserialize(tempFile);
1515      CollectionAssert.AreEqual(s, newS);
1516    }
1517
1518    [TestMethod]
1519    [TestCategory("Persistence")]
1520    [TestProperty("Time", "short")]
1521    public void TestUnicode() {
1522      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1523      XmlGenerator.Serialize(s, tempFile);
1524      var newS = XmlParser.Deserialize(tempFile);
1525      Assert.AreEqual(s, newS);
1526    }
1527
1528    [TestMethod]
1529    [TestCategory("Persistence")]
1530    [TestProperty("Time", "short")]
1531    public void TestQueue() {
1532      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
1533      XmlGenerator.Serialize(q, tempFile);
1534      var newQ = (Queue<int>)XmlParser.Deserialize(tempFile);
1535      CollectionAssert.AreEqual(q, newQ);
1536    }
1537
1538
1539
1540    [ClassInitialize]
1541    public static void Initialize(TestContext testContext) {
1542      ConfigurationService.Instance.Reset();
1543    }
1544  }
1545}
Note: See TracBrowser for help on using the repository browser.