Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1734 was 1734, checked in by epitzer, 15 years ago

Serialization with streams. (#603)

File size: 17.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 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  public class NonSerializable {
177    int x;
178  }
179
180
181  [TestClass]
182  public class UseCases {
183
184    private string tempFile;
185
186    [TestInitialize()]
187    public void CreateTempFile() {
188      tempFile = Path.GetTempFileName();
189    }
190
191    [TestCleanup()]
192    public void ClearTempFile() {
193      StreamReader reader = new StreamReader(tempFile);
194      string s = reader.ReadToEnd();
195      reader.Close();
196      File.Delete(tempFile);
197    }
198
199    [TestMethod]
200    public void ComplexStorable() {
201      Root r = new Root();
202      r.intStack.Push(1);
203      r.intStack.Push(2);
204      r.intStack.Push(3);
205      r.selfReferences = new List<Root> { r, r };
206      r.c = new Custom { r = r };
207      r.dict.Add("one", 1);
208      r.dict.Add("two", 2);
209      r.dict.Add("three", 3);
210      r.myEnum = TestEnum.va1;
211      r.i = new[] { 7, 5, 6 };
212      r.s = "new value";
213      r.intArray = new ArrayList { 3, 2, 1 };
214      r.intList = new List<int> { 9, 8, 7 };
215      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
216      r.boolean = false;
217      r.dateTime = DateTime.Now;
218      r.kvp = new KeyValuePair<string, int>("string key", 321);
219      r.uninitialized = null;
220      XmlGenerator.Serialize(r, tempFile);
221      Root newR = (Root)XmlParser.Deserialize(tempFile);
222      Assert.AreEqual(
223        DebugStringGenerator.Serialize(r),
224        DebugStringGenerator.Serialize(newR));
225      Assert.AreSame(newR, newR.selfReferences[0]);
226      Assert.AreNotSame(r, newR);
227      Assert.AreEqual(r.myEnum, TestEnum.va1);
228      Assert.AreEqual(r.i[0], 7);
229      Assert.AreEqual(r.i[1], 5);
230      Assert.AreEqual(r.i[2], 6);
231      Assert.AreEqual(r.s, "new value");
232      Assert.AreEqual(r.intArray[0], 3);
233      Assert.AreEqual(r.intArray[1], 2);
234      Assert.AreEqual(r.intArray[2], 1);
235      Assert.AreEqual(r.intList[0], 9);
236      Assert.AreEqual(r.intList[1], 8);
237      Assert.AreEqual(r.intList[2], 7);
238      Assert.AreEqual(r.multiDimArray[0, 0], 5);
239      Assert.AreEqual(r.multiDimArray[0, 1], 4);
240      Assert.AreEqual(r.multiDimArray[0, 2], 3);
241      Assert.AreEqual(r.multiDimArray[1, 0], 1);
242      Assert.AreEqual(r.multiDimArray[1, 1], 4);
243      Assert.AreEqual(r.multiDimArray[1, 2], 6);
244      Assert.IsFalse(r.boolean);
245      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
246      Assert.AreEqual(r.kvp.Key, "string key");
247      Assert.AreEqual(r.kvp.Value, 321);
248      Assert.IsNull(r.uninitialized);
249      Assert.AreEqual(newR.myEnum, TestEnum.va1);
250      Assert.AreEqual(newR.i[0], 7);
251      Assert.AreEqual(newR.i[1], 5);
252      Assert.AreEqual(newR.i[2], 6);
253      Assert.AreEqual(newR.s, "new value");
254      Assert.AreEqual(newR.intArray[0], 3);
255      Assert.AreEqual(newR.intArray[1], 2);
256      Assert.AreEqual(newR.intArray[2], 1);
257      Assert.AreEqual(newR.intList[0], 9);
258      Assert.AreEqual(newR.intList[1], 8);
259      Assert.AreEqual(newR.intList[2], 7);
260      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
261      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
262      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
263      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
264      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
265      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
266      Assert.AreEqual(newR.intStack.Pop(), 3);
267      Assert.AreEqual(newR.intStack.Pop(), 2);
268      Assert.AreEqual(newR.intStack.Pop(), 1);
269      Assert.IsFalse(newR.boolean);
270      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
271      Assert.AreEqual(newR.kvp.Key, "string key");
272      Assert.AreEqual(newR.kvp.Value, 321);
273      Assert.IsNull(newR.uninitialized);
274    }
275
276    [TestMethod]
277    public void SelfReferences() {
278      C c = new C();
279      C[][] cs = new C[2][];
280      cs[0] = new C[] { c };
281      cs[1] = new C[] { c };
282      c.allCs = cs;
283      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
284      XmlGenerator.Serialize(cs, tempFile);
285      object o = XmlParser.Deserialize(tempFile);
286      Assert.AreEqual(
287        DebugStringGenerator.Serialize(cs),
288        DebugStringGenerator.Serialize(o));
289      Assert.AreSame(c, c.allCs[0][0]);
290      Assert.AreSame(c, c.allCs[1][0]);
291      Assert.AreSame(c, c.kvpList.Key[0]);
292      Assert.AreSame(c, c.kvpList.Value);
293      C[][] newCs = (C[][])o;
294      C newC = newCs[0][0];
295      Assert.AreSame(newC, newC.allCs[0][0]);
296      Assert.AreSame(newC, newC.allCs[1][0]);
297      Assert.AreSame(newC, newC.kvpList.Key[0]);
298      Assert.AreSame(newC, newC.kvpList.Value);
299    }
300
301    [TestMethod]
302    public void ArrayCreation() {
303      ArrayList[] arrayListArray = new ArrayList[4];
304      arrayListArray[0] = new ArrayList();
305      arrayListArray[0].Add(arrayListArray);
306      arrayListArray[0].Add(arrayListArray);
307      arrayListArray[1] = new ArrayList();
308      arrayListArray[1].Add(arrayListArray);
309      arrayListArray[2] = new ArrayList();
310      arrayListArray[2].Add(arrayListArray);
311      arrayListArray[2].Add(arrayListArray);
312      Array a = Array.CreateInstance(
313                              typeof(object),
314                              new[] { 1, 2 }, new[] { 3, 4 });
315      arrayListArray[2].Add(a);
316      XmlGenerator.Serialize(arrayListArray, tempFile);
317      object o = XmlParser.Deserialize(tempFile);
318      Assert.AreEqual(
319        DebugStringGenerator.Serialize(arrayListArray),
320        DebugStringGenerator.Serialize(o));
321      ArrayList[] newArray = (ArrayList[])o;
322      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
323      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
324      Assert.AreSame(newArray, newArray[0][0]);
325      Assert.AreSame(newArray, newArray[2][1]);
326    }
327
328    [TestMethod]
329    public void CustomSerializationProperty() {
330      Manager m = new Manager();
331      XmlGenerator.Serialize(m, tempFile);
332      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
333      Assert.AreNotEqual(
334        DebugStringGenerator.Serialize(m),
335        DebugStringGenerator.Serialize(newM));
336      Assert.AreEqual(m.dbl, newM.dbl);
337      Assert.AreEqual(m.lastLoadTime, new DateTime());
338      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
339      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
340    }
341
342    [TestMethod]
343    public void Primitives() {
344      PrimitivesTest sdt = new PrimitivesTest();
345      XmlGenerator.Serialize(sdt, tempFile);
346      object o = XmlParser.Deserialize(tempFile);
347      Assert.AreEqual(
348        DebugStringGenerator.Serialize(sdt),
349        DebugStringGenerator.Serialize(o));
350    }
351
352    [TestMethod]
353    public void MultiDimensionalArray() {
354      string[,] mDimString = new string[,] {
355        {"ora", "et", "labora"},
356        {"Beten", "und", "Arbeiten"}
357      };
358      XmlGenerator.Serialize(mDimString, tempFile);
359      object o = XmlParser.Deserialize(tempFile);
360      Assert.AreEqual(
361        DebugStringGenerator.Serialize(mDimString),
362        DebugStringGenerator.Serialize(o));
363    }
364
365    public class NestedType {
366      [Storable]
367      private string value = "value";
368    }
369
370    [TestMethod]
371    public void NestedTypeTest() {
372      NestedType t = new NestedType();
373      XmlGenerator.Serialize(t, tempFile);
374      object o = XmlParser.Deserialize(tempFile);
375      Assert.AreEqual(
376        DebugStringGenerator.Serialize(t),
377        DebugStringGenerator.Serialize(o));
378    }
379
380
381    [TestMethod]
382    public void SimpleArray() {
383      string[] strings = { "ora", "et", "labora" };
384      XmlGenerator.Serialize(strings, tempFile);
385      object o = XmlParser.Deserialize(tempFile);
386      Assert.AreEqual(
387        DebugStringGenerator.Serialize(strings),
388        DebugStringGenerator.Serialize(o));
389    }
390
391    [TestMethod]
392    public void BinaryFormatTest() {
393      Root r = new Root();
394      Assert.Fail("Not Implemented");
395      //BinaryGenerator.Serialize(r, "test.bin");
396    }
397
398
399    [TestMethod]
400    public void PrimitiveRoot() {
401      XmlGenerator.Serialize(12.3f, tempFile);
402      object o = XmlParser.Deserialize(tempFile);
403      Assert.AreEqual(
404        DebugStringGenerator.Serialize(12.3f),
405        DebugStringGenerator.Serialize(o));
406    }
407
408    private string formatFullMemberName(MemberInfo mi) {
409      return new StringBuilder()
410        .Append(mi.DeclaringType.Assembly.GetName().Name)
411        .Append(": ")
412        .Append(mi.DeclaringType.Namespace)
413        .Append('.')
414        .Append(mi.DeclaringType.Name)
415        .Append('.')
416        .Append(mi.Name).ToString();
417    }
418
419    [TestMethod]
420    public void CodingConventions() {
421      List<string> lowerCaseMethodNames = new List<string>();
422      List<string> lowerCaseProperties = new List<string>();
423      List<string> lowerCaseFields = new List<string>();
424      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
425        if (!a.GetName().Name.StartsWith("HeuristicLab"))
426          continue;
427        foreach (Type t in a.GetTypes()) {
428          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
429            if (char.IsLower(mi.Name[0])) {
430              if (mi.MemberType == MemberTypes.Field)
431                lowerCaseFields.Add(formatFullMemberName(mi));
432              if (mi.MemberType == MemberTypes.Property)
433                lowerCaseProperties.Add(formatFullMemberName(mi));
434              if (mi.MemberType == MemberTypes.Method &&
435                !mi.Name.StartsWith("get_") &&
436                !mi.Name.StartsWith("set_") &&
437                !mi.Name.StartsWith("add_") &&
438                !mi.Name.StartsWith("remove_"))
439                lowerCaseMethodNames.Add(formatFullMemberName(mi));
440            }
441          }
442        }
443      }
444      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
445      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
446      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
447    }
448
449    [TestMethod]
450    public void Number2StringDecomposer() {
451      NumberTest sdt = new NumberTest();
452      XmlGenerator.Serialize(sdt, tempFile,
453        new Configuration(new XmlFormat(),
454          new List<IFormatter> { new String2XmlFormatter() },
455          new List<IDecomposer> {
456            new StorableDecomposer(),
457            new Number2StringDecomposer() }));
458      object o = XmlParser.Deserialize(tempFile);
459      Assert.AreEqual(
460        DebugStringGenerator.Serialize(sdt),
461        DebugStringGenerator.Serialize(o));
462    }
463
464    [TestMethod]
465    public void Events() {
466      EventTest et = new EventTest();
467      et.OnChange += (o) => o;
468      XmlGenerator.Serialize(et, tempFile);
469      EventTest newEt = (EventTest)XmlParser.Deserialize(tempFile);
470    }
471
472    [TestMethod]
473    public void Enums() {
474      EnumTest et = new EnumTest();
475      et.simpleEnum = SimpleEnum.two;
476      et.complexEnum = ComplexEnum.three;
477      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
478      XmlGenerator.Serialize(et, tempFile);
479      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
480      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
481      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
482      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
483    }
484
485    [TestMethod]
486    public void TestAliasingWithOverriddenEquals() {
487      List<IntWrapper> ints = new List<IntWrapper>();
488      ints.Add(new IntWrapper(1));
489      ints.Add(new IntWrapper(1));
490      Assert.AreEqual(ints[0], ints[1]);
491      Assert.AreNotSame(ints[0], ints[1]);
492      XmlGenerator.Serialize(ints, tempFile);
493      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
494      Assert.AreEqual(newInts[0].Value, 1);
495      Assert.AreEqual(newInts[1].Value, 1);
496      Assert.AreEqual(newInts[0], newInts[1]);
497      Assert.AreNotSame(newInts[0], newInts[1]);
498    }
499
500    [TestMethod]
501    public void NonDefaultConstructorTest() {
502      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
503      try {
504        XmlGenerator.Serialize(c, tempFile);
505        Assert.Fail("Exception not thrown");
506      } catch (PersistenceException) {
507      }
508    }
509
510    [TestMethod]
511    public void TestSavingException() {     
512      List<int> list = new List<int> { 1, 2, 3 };
513      XmlGenerator.Serialize(list, tempFile);
514      NonSerializable s = new NonSerializable();
515      try {
516        XmlGenerator.Serialize(s, tempFile);
517        Assert.Fail("Exception expected");
518      } catch (PersistenceException) { }
519      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
520      Assert.AreEqual(list[0], newList[0]);
521      Assert.AreEqual(list[1], newList[1]);
522    }
523
524    [ClassInitialize]
525    public static void Initialize(TestContext testContext) {
526      ConfigurationService.Instance.Reset();
527    }
528  }
529}
Note: See TracBrowser for help on using the repository browser.