Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/UnitTests/UseCases.cs @ 1728

Last change on this file since 1728 was 1705, checked in by epitzer, 16 years ago

Check for default constructor in all decomposers to ensure failure during serialization instead of deserialization. (#606)

File size: 16.6 KB
Line 
1using System;
2using System.Text;
3using System.Collections.Generic;
4using System.Linq;
5using Microsoft.VisualStudio.TestTools.UnitTesting;
6using HeuristicLab.Persistence.Core;
7using System.Collections;
8using HeuristicLab.Persistence.Default.Xml;
9using HeuristicLab.Persistence.Default.DebugString;
10using System.IO;
11using System.Reflection;
12using HeuristicLab.Persistence.Default.Decomposers.Storable;
13using HeuristicLab.Persistence.Interfaces;
14using HeuristicLab.Persistence.Default.Xml.Primitive;
15using HeuristicLab.Persistence.Default.Decomposers;
16
17namespace HeuristicLab.Persistence.UnitTest {
18
19  public class NumberTest {
20    [Storable]
21    private bool _bool = true;
22    [Storable]
23    private byte _byte = 0xFF;
24    [Storable]
25    private sbyte _sbyte = 0xF;
26    [Storable]
27    private short _short = -123;
28    [Storable]
29    private ushort _ushort = 123;
30    [Storable]
31    private int _int = -123;
32    [Storable]
33    private uint _uint = 123;
34    [Storable]
35    private long _long = 123456;
36    [Storable]
37    private ulong _ulong = 123456;
38  }
39
40  public class NonDefaultConstructorClass {
41    [Storable]
42    int value;
43    public NonDefaultConstructorClass(int value) {
44      this.value = value;
45    }
46  }
47
48  public class IntWrapper {
49
50    [Storable]
51    public int Value;
52
53    private IntWrapper() { }
54
55    public IntWrapper(int value) {
56      this.Value = value;
57    }
58
59    public override bool Equals(object obj) {
60      if (obj as IntWrapper == null)
61        return false;
62      return Value.Equals(((IntWrapper)obj).Value);
63    }
64    public override int GetHashCode() {
65      return Value.GetHashCode();
66    }
67
68  }
69
70  public class EventTest {
71    public delegate object Filter(object o);
72    public event Filter OnChange;
73    [Storable]
74    private Delegate[] OnChangeListener {
75      get { return OnChange.GetInvocationList(); }
76      set {
77        foreach (Delegate d in value) {
78          OnChange += (Filter)d;
79        }
80      }
81    }
82  }
83
84  public class PrimitivesTest : NumberTest {
85    [Storable]
86    private char c = 'e';
87    [Storable]
88    private long[,] _long_array =
89      new long[,] { { 123, 456, }, { 789, 123 } };
90    [Storable]
91    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
92    [Storable]
93    private object o = new object();
94  }
95
96  public enum TestEnum { va1, va2, va3, va8 } ;
97
98  public class RootBase {
99    [Storable]
100    private string baseString = "   Serial  ";
101    [Storable]
102    public TestEnum myEnum = TestEnum.va3;
103  }
104
105  public class Root : RootBase {
106    [Storable]
107    public Stack<int> intStack = new Stack<int>();
108    [Storable]
109    public int[] i = new[] { 3, 4, 5, 6 };
110    [Storable(Name = "Test String")]
111    public string s;
112    [Storable]
113    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
114    [Storable]
115    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
116    [Storable]
117    public Custom c;
118    [Storable]
119    public List<Root> selfReferences;
120    [Storable]
121    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
122    [Storable]
123    public bool boolean = true;
124    [Storable]
125    public DateTime dateTime;
126    [Storable]
127    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
128    [Storable]
129    public Dictionary<string, int> dict = new Dictionary<string, int>();
130    [Storable(DefaultValue = "default")]
131    public string uninitialized;
132  }
133
134  public enum SimpleEnum { one, two, three }
135  public enum ComplexEnum { one = 1, two = 2, three = 3 }
136  [FlagsAttribute]
137  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
138
139  public class EnumTest {
140    [Storable]
141    public SimpleEnum simpleEnum = SimpleEnum.one;
142    [Storable]
143    public ComplexEnum complexEnum = (ComplexEnum)2;
144    [Storable]
145    public TrickyEnum trickyEnum = (TrickyEnum)15;
146  }
147
148  public class Custom {
149    [Storable]
150    public int i;
151    [Storable]
152    public Root r;
153    [Storable]
154    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
155  }
156
157  public class Manager {
158
159    public DateTime lastLoadTime;
160    [Storable]
161    private DateTime lastLoadTimePersistence {
162      get { return lastLoadTime; }
163      set { lastLoadTime = DateTime.Now; }
164    }
165    [Storable]
166    public double? dbl;
167  }
168
169  public class C {
170    [Storable]
171    public C[][] allCs;
172    [Storable]
173    public KeyValuePair<List<C>, C> kvpList;
174  }
175
176
177  [TestClass]
178  public class UseCases {
179
180    private string tempFile;
181
182    [TestInitialize()]
183    public void CreateTempFile() {
184      tempFile = Path.GetTempFileName();
185    }
186
187    [TestCleanup()]
188    public void ClearTempFile() {
189      StreamReader reader = new StreamReader(tempFile);
190      string s = reader.ReadToEnd();
191      reader.Close();
192      File.Delete(tempFile);
193    }
194
195    [TestMethod]
196    public void ComplexStorable() {
197      Root r = new Root();
198      r.intStack.Push(1);
199      r.intStack.Push(2);
200      r.intStack.Push(3);
201      r.selfReferences = new List<Root> { r, r };
202      r.c = new Custom { r = r };
203      r.dict.Add("one", 1);
204      r.dict.Add("two", 2);
205      r.dict.Add("three", 3);
206      r.myEnum = TestEnum.va1;
207      r.i = new[] { 7, 5, 6 };
208      r.s = "new value";
209      r.intArray = new ArrayList { 3, 2, 1 };
210      r.intList = new List<int> { 9, 8, 7 };
211      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
212      r.boolean = false;
213      r.dateTime = DateTime.Now;
214      r.kvp = new KeyValuePair<string, int>("string key", 321);
215      r.uninitialized = null;
216      XmlGenerator.Serialize(r, tempFile);
217      Root newR = (Root)XmlParser.DeSerialize(tempFile);
218      Assert.AreEqual(
219        DebugStringGenerator.Serialize(r),
220        DebugStringGenerator.Serialize(newR));
221      Assert.AreSame(newR, newR.selfReferences[0]);
222      Assert.AreNotSame(r, newR);
223      Assert.AreEqual(r.myEnum, TestEnum.va1);
224      Assert.AreEqual(r.i[0], 7);
225      Assert.AreEqual(r.i[1], 5);
226      Assert.AreEqual(r.i[2], 6);
227      Assert.AreEqual(r.s, "new value");
228      Assert.AreEqual(r.intArray[0], 3);
229      Assert.AreEqual(r.intArray[1], 2);
230      Assert.AreEqual(r.intArray[2], 1);
231      Assert.AreEqual(r.intList[0], 9);
232      Assert.AreEqual(r.intList[1], 8);
233      Assert.AreEqual(r.intList[2], 7);
234      Assert.AreEqual(r.multiDimArray[0, 0], 5);
235      Assert.AreEqual(r.multiDimArray[0, 1], 4);
236      Assert.AreEqual(r.multiDimArray[0, 2], 3);
237      Assert.AreEqual(r.multiDimArray[1, 0], 1);
238      Assert.AreEqual(r.multiDimArray[1, 1], 4);
239      Assert.AreEqual(r.multiDimArray[1, 2], 6);
240      Assert.IsFalse(r.boolean);
241      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
242      Assert.AreEqual(r.kvp.Key, "string key");
243      Assert.AreEqual(r.kvp.Value, 321);
244      Assert.IsNull(r.uninitialized);
245      Assert.AreEqual(newR.myEnum, TestEnum.va1);
246      Assert.AreEqual(newR.i[0], 7);
247      Assert.AreEqual(newR.i[1], 5);
248      Assert.AreEqual(newR.i[2], 6);
249      Assert.AreEqual(newR.s, "new value");
250      Assert.AreEqual(newR.intArray[0], 3);
251      Assert.AreEqual(newR.intArray[1], 2);
252      Assert.AreEqual(newR.intArray[2], 1);
253      Assert.AreEqual(newR.intList[0], 9);
254      Assert.AreEqual(newR.intList[1], 8);
255      Assert.AreEqual(newR.intList[2], 7);
256      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
257      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
258      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
259      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
260      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
261      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
262      Assert.AreEqual(newR.intStack.Pop(), 3);
263      Assert.AreEqual(newR.intStack.Pop(), 2);
264      Assert.AreEqual(newR.intStack.Pop(), 1);
265      Assert.IsFalse(newR.boolean);
266      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
267      Assert.AreEqual(newR.kvp.Key, "string key");
268      Assert.AreEqual(newR.kvp.Value, 321);
269      Assert.IsNull(newR.uninitialized);
270    }
271
272    [TestMethod]
273    public void SelfReferences() {
274      C c = new C();
275      C[][] cs = new C[2][];
276      cs[0] = new C[] { c };
277      cs[1] = new C[] { c };
278      c.allCs = cs;
279      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
280      XmlGenerator.Serialize(cs, tempFile);
281      object o = XmlParser.DeSerialize(tempFile);
282      Assert.AreEqual(
283        DebugStringGenerator.Serialize(cs),
284        DebugStringGenerator.Serialize(o));
285      Assert.AreSame(c, c.allCs[0][0]);
286      Assert.AreSame(c, c.allCs[1][0]);
287      Assert.AreSame(c, c.kvpList.Key[0]);
288      Assert.AreSame(c, c.kvpList.Value);
289      C[][] newCs = (C[][])o;
290      C newC = newCs[0][0];
291      Assert.AreSame(newC, newC.allCs[0][0]);
292      Assert.AreSame(newC, newC.allCs[1][0]);
293      Assert.AreSame(newC, newC.kvpList.Key[0]);
294      Assert.AreSame(newC, newC.kvpList.Value);
295    }
296
297    [TestMethod]
298    public void ArrayCreation() {
299      ArrayList[] arrayListArray = new ArrayList[4];
300      arrayListArray[0] = new ArrayList();
301      arrayListArray[0].Add(arrayListArray);
302      arrayListArray[0].Add(arrayListArray);
303      arrayListArray[1] = new ArrayList();
304      arrayListArray[1].Add(arrayListArray);
305      arrayListArray[2] = new ArrayList();
306      arrayListArray[2].Add(arrayListArray);
307      arrayListArray[2].Add(arrayListArray);
308      Array a = Array.CreateInstance(
309                              typeof(object),
310                              new[] { 1, 2 }, new[] { 3, 4 });
311      arrayListArray[2].Add(a);
312      XmlGenerator.Serialize(arrayListArray, tempFile);
313      object o = XmlParser.DeSerialize(tempFile);
314      Assert.AreEqual(
315        DebugStringGenerator.Serialize(arrayListArray),
316        DebugStringGenerator.Serialize(o));
317      ArrayList[] newArray = (ArrayList[])o;
318      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
319      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
320      Assert.AreSame(newArray, newArray[0][0]);
321      Assert.AreSame(newArray, newArray[2][1]);
322    }
323
324    [TestMethod]
325    public void CustomSerializationProperty() {
326      Manager m = new Manager();
327      XmlGenerator.Serialize(m, tempFile);
328      Manager newM = (Manager)XmlParser.DeSerialize(tempFile);
329      Assert.AreNotEqual(
330        DebugStringGenerator.Serialize(m),
331        DebugStringGenerator.Serialize(newM));
332      Assert.AreEqual(m.dbl, newM.dbl);
333      Assert.AreEqual(m.lastLoadTime, new DateTime());
334      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
335      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
336    }
337
338    [TestMethod]
339    public void Primitives() {
340      PrimitivesTest sdt = new PrimitivesTest();
341      XmlGenerator.Serialize(sdt, tempFile);
342      object o = XmlParser.DeSerialize(tempFile);
343      Assert.AreEqual(
344        DebugStringGenerator.Serialize(sdt),
345        DebugStringGenerator.Serialize(o));
346    }
347
348    [TestMethod]
349    public void MultiDimensionalArray() {
350      string[,] mDimString = new string[,] {
351        {"ora", "et", "labora"},
352        {"Beten", "und", "Arbeiten"}
353      };
354      XmlGenerator.Serialize(mDimString, tempFile);
355      object o = XmlParser.DeSerialize(tempFile);
356      Assert.AreEqual(
357        DebugStringGenerator.Serialize(mDimString),
358        DebugStringGenerator.Serialize(o));
359    }
360
361    public class NestedType {
362      [Storable]
363      private string value = "value";
364    }
365
366    [TestMethod]
367    public void NestedTypeTest() {
368      NestedType t = new NestedType();
369      XmlGenerator.Serialize(t, tempFile);
370      object o = XmlParser.DeSerialize(tempFile);
371      Assert.AreEqual(
372        DebugStringGenerator.Serialize(t),
373        DebugStringGenerator.Serialize(o));
374    }
375
376
377    [TestMethod]
378    public void SimpleArray() {
379      string[] strings = { "ora", "et", "labora" };
380      XmlGenerator.Serialize(strings, tempFile);
381      object o = XmlParser.DeSerialize(tempFile);
382      Assert.AreEqual(
383        DebugStringGenerator.Serialize(strings),
384        DebugStringGenerator.Serialize(o));
385    }
386
387    [TestMethod]
388    public void BinaryFormatTest() {
389      Root r = new Root();
390      Assert.Fail("Not Implemented");
391      //BinaryGenerator.Serialize(r, "test.bin");
392    }
393
394
395    [TestMethod]
396    public void PrimitiveRoot() {
397      XmlGenerator.Serialize(12.3f, tempFile);
398      object o = XmlParser.DeSerialize(tempFile);
399      Assert.AreEqual(
400        DebugStringGenerator.Serialize(12.3f),
401        DebugStringGenerator.Serialize(o));
402    }
403
404    private string formatFullMemberName(MemberInfo mi) {
405      return new StringBuilder()
406        .Append(mi.DeclaringType.Assembly.GetName().Name)
407        .Append(": ")
408        .Append(mi.DeclaringType.Namespace)
409        .Append('.')
410        .Append(mi.DeclaringType.Name)
411        .Append('.')
412        .Append(mi.Name).ToString();
413    }
414
415    [TestMethod]
416    public void CodingConventions() {
417      List<string> lowerCaseMethodNames = new List<string>();
418      List<string> lowerCaseProperties = new List<string>();
419      List<string> lowerCaseFields = new List<string>();
420      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
421        if (!a.GetName().Name.StartsWith("HeuristicLab"))
422          continue;
423        foreach (Type t in a.GetTypes()) {
424          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
425            if (char.IsLower(mi.Name[0])) {
426              if (mi.MemberType == MemberTypes.Field)
427                lowerCaseFields.Add(formatFullMemberName(mi));
428              if (mi.MemberType == MemberTypes.Property)
429                lowerCaseProperties.Add(formatFullMemberName(mi));
430              if (mi.MemberType == MemberTypes.Method &&
431                !mi.Name.StartsWith("get_") &&
432                !mi.Name.StartsWith("set_") &&
433                !mi.Name.StartsWith("add_") &&
434                !mi.Name.StartsWith("remove_"))
435                lowerCaseMethodNames.Add(formatFullMemberName(mi));
436            }
437          }
438        }
439      }
440      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
441      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
442      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
443    }
444
445    [TestMethod]
446    public void Number2StringDecomposer() {
447      NumberTest sdt = new NumberTest();
448      XmlGenerator.Serialize(sdt, tempFile,
449        new Configuration(new XmlFormat(),
450          new List<IFormatter> { new String2XmlFormatter() },
451          new List<IDecomposer> {
452            new StorableDecomposer(),
453            new Number2StringDecomposer() }));
454      object o = XmlParser.DeSerialize(tempFile);
455      Assert.AreEqual(
456        DebugStringGenerator.Serialize(sdt),
457        DebugStringGenerator.Serialize(o));
458    }
459
460    [TestMethod]
461    public void Events() {
462      EventTest et = new EventTest();
463      et.OnChange += (o) => o;
464      XmlGenerator.Serialize(et, tempFile);
465      EventTest newEt = (EventTest)XmlParser.DeSerialize(tempFile);
466    }
467
468    [TestMethod]
469    public void Enums() {
470      EnumTest et = new EnumTest();
471      et.simpleEnum = SimpleEnum.two;
472      et.complexEnum = ComplexEnum.three;
473      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
474      XmlGenerator.Serialize(et, tempFile);
475      EnumTest newEt = (EnumTest)XmlParser.DeSerialize(tempFile);
476      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
477      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
478      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
479    }
480
481    [TestMethod]
482    public void TestAliasingWithOverriddenEquals() {
483      List<IntWrapper> ints = new List<IntWrapper>();
484      ints.Add(new IntWrapper(1));
485      ints.Add(new IntWrapper(1));
486      Assert.AreEqual(ints[0], ints[1]);
487      Assert.AreNotSame(ints[0], ints[1]);
488      XmlGenerator.Serialize(ints, tempFile);
489      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.DeSerialize(tempFile);
490      Assert.AreEqual(newInts[0].Value, 1);
491      Assert.AreEqual(newInts[1].Value, 1);
492      Assert.AreEqual(newInts[0], newInts[1]);
493      Assert.AreNotSame(newInts[0], newInts[1]);
494    }
495
496    [TestMethod]
497    public void NonDefaultConstructorTest() {
498      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
499      try {
500        XmlGenerator.Serialize(c, tempFile);
501        Assert.Fail("Exception not thrown");
502      } catch (PersistenceException) {
503      }
504    }
505
506    [ClassInitialize]
507    public static void Initialize(TestContext testContext) {
508      ConfigurationService.Instance.Reset();
509    }
510  }
511}
Note: See TracBrowser for help on using the repository browser.