Free cookie consent management tool by TermsFeed Policy Generator

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

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

Replace value comparison with references comparison in serializer. (#605)

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