Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fix EnumDecomposer to be applicable for flag enums and enums without names. (#603)

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