Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone2/sources/HeuristicLab.Persistence/UnitTests/UseCases.cs @ 1835

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

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

File size: 18.5 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.CompositeSerializers.Storable;
13using HeuristicLab.Persistence.Interfaces;
14using HeuristicLab.Persistence.Default.Xml.Primitive;
15using HeuristicLab.Persistence.Default.CompositeSerializers;
16using HeuristicLab.Persistence.Auxiliary;
17using System.Text.RegularExpressions;
18
19namespace HeuristicLab.Persistence.UnitTest {
20
21  public class NumberTest {
22    [Storable]
23    private bool _bool = true;
24    [Storable]
25    private byte _byte = 0xFF;
26    [Storable]
27    private sbyte _sbyte = 0xF;
28    [Storable]
29    private short _short = -123;
30    [Storable]
31    private ushort _ushort = 123;
32    [Storable]
33    private int _int = -123;
34    [Storable]
35    private uint _uint = 123;
36    [Storable]
37    private long _long = 123456;
38    [Storable]
39    private ulong _ulong = 123456;
40  }
41
42  public class NonDefaultConstructorClass {
43    [Storable]
44    int value;
45    public NonDefaultConstructorClass(int value) {
46      this.value = value;
47    }
48  }
49
50  public class IntWrapper {
51
52    [Storable]
53    public int Value;
54
55    private IntWrapper() { }
56
57    public IntWrapper(int value) {
58      this.Value = value;
59    }
60
61    public override bool Equals(object obj) {
62      if (obj as IntWrapper == null)
63        return false;
64      return Value.Equals(((IntWrapper)obj).Value);
65    }
66    public override int GetHashCode() {
67      return Value.GetHashCode();
68    }
69
70  }
71
72  public class PrimitivesTest : NumberTest {
73    [Storable]
74    private char c = 'e';
75    [Storable]
76    private long[,] _long_array =
77      new long[,] { { 123, 456, }, { 789, 123 } };
78    [Storable]
79    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
80    [Storable]
81    private object o = new object();
82  }
83
84  public enum TestEnum { va1, va2, va3, va8 } ;
85
86  public class RootBase {
87    [Storable]
88    private string baseString = "   Serial  ";
89    [Storable]
90    public TestEnum myEnum = TestEnum.va3;
91  }
92
93  public class Root : RootBase {
94    [Storable]
95    public Stack<int> intStack = new Stack<int>();
96    [Storable]
97    public int[] i = new[] { 3, 4, 5, 6 };
98    [Storable(Name = "Test String")]
99    public string s;
100    [Storable]
101    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
102    [Storable]
103    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
104    [Storable]
105    public Custom c;
106    [Storable]
107    public List<Root> selfReferences;
108    [Storable]
109    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
110    [Storable]
111    public bool boolean = true;
112    [Storable]
113    public DateTime dateTime;
114    [Storable]
115    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
116    [Storable]
117    public Dictionary<string, int> dict = new Dictionary<string, int>();
118    [Storable(DefaultValue = "default")]
119    public string uninitialized;
120  }
121
122  public enum SimpleEnum { one, two, three }
123  public enum ComplexEnum { one = 1, two = 2, three = 3 }
124  [FlagsAttribute]
125  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
126
127  public class EnumTest {
128    [Storable]
129    public SimpleEnum simpleEnum = SimpleEnum.one;
130    [Storable]
131    public ComplexEnum complexEnum = (ComplexEnum)2;
132    [Storable]
133    public TrickyEnum trickyEnum = (TrickyEnum)15;
134  }
135
136  public class Custom {
137    [Storable]
138    public int i;
139    [Storable]
140    public Root r;
141    [Storable]
142    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
143  }
144
145  public class Manager {
146
147    public DateTime lastLoadTime;
148    [Storable]
149    private DateTime lastLoadTimePersistence {
150      get { return lastLoadTime; }
151      set { lastLoadTime = DateTime.Now; }
152    }
153    [Storable]
154    public double? dbl;
155  }
156
157  public class C {
158    [Storable]
159    public C[][] allCs;
160    [Storable]
161    public KeyValuePair<List<C>, C> kvpList;
162  }
163
164  public class NonSerializable {
165    int x;
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 PrimitiveRoot() {
381      XmlGenerator.Serialize(12.3f, tempFile);
382      object o = XmlParser.Deserialize(tempFile);
383      Assert.AreEqual(
384        DebugStringGenerator.Serialize(12.3f),
385        DebugStringGenerator.Serialize(o));
386    }
387
388    private string formatFullMemberName(MemberInfo mi) {
389      return new StringBuilder()
390        .Append(mi.DeclaringType.Assembly.GetName().Name)
391        .Append(": ")
392        .Append(mi.DeclaringType.Namespace)
393        .Append('.')
394        .Append(mi.DeclaringType.Name)
395        .Append('.')
396        .Append(mi.Name).ToString();
397    }
398
399    [TestMethod]
400    public void CodingConventions() {
401      List<string> lowerCaseMethodNames = new List<string>();
402      List<string> lowerCaseProperties = new List<string>();
403      List<string> lowerCaseFields = new List<string>();
404      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
405        if (!a.GetName().Name.StartsWith("HeuristicLab"))
406          continue;
407        foreach (Type t in a.GetTypes()) {
408          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
409            if (char.IsLower(mi.Name[0])) {
410              if (mi.MemberType == MemberTypes.Field)
411                lowerCaseFields.Add(formatFullMemberName(mi));
412              if (mi.MemberType == MemberTypes.Property)
413                lowerCaseProperties.Add(formatFullMemberName(mi));
414              if (mi.MemberType == MemberTypes.Method &&
415                !mi.Name.StartsWith("get_") &&
416                !mi.Name.StartsWith("set_") &&
417                !mi.Name.StartsWith("add_") &&
418                !mi.Name.StartsWith("remove_"))
419                lowerCaseMethodNames.Add(formatFullMemberName(mi));
420            }
421          }
422        }
423      }
424      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
425      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
426      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
427    }
428
429    [TestMethod]
430    public void Number2StringDecomposer() {
431      NumberTest sdt = new NumberTest();
432      XmlGenerator.Serialize(sdt, tempFile,
433        new Configuration(new XmlFormat(),
434          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
435          new List<ICompositeSerializer> {
436            new StorableSerializer(),
437            new Number2StringSerializer() }));
438      object o = XmlParser.Deserialize(tempFile);
439      Assert.AreEqual(
440        DebugStringGenerator.Serialize(sdt),
441        DebugStringGenerator.Serialize(o));
442    }
443
444    [TestMethod]
445    public void Enums() {
446      EnumTest et = new EnumTest();
447      et.simpleEnum = SimpleEnum.two;
448      et.complexEnum = ComplexEnum.three;
449      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
450      XmlGenerator.Serialize(et, tempFile);
451      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
452      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
453      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
454      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
455    }
456
457    [TestMethod]
458    public void TestAliasingWithOverriddenEquals() {
459      List<IntWrapper> ints = new List<IntWrapper>();
460      ints.Add(new IntWrapper(1));
461      ints.Add(new IntWrapper(1));
462      Assert.AreEqual(ints[0], ints[1]);
463      Assert.AreNotSame(ints[0], ints[1]);
464      XmlGenerator.Serialize(ints, tempFile);
465      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
466      Assert.AreEqual(newInts[0].Value, 1);
467      Assert.AreEqual(newInts[1].Value, 1);
468      Assert.AreEqual(newInts[0], newInts[1]);
469      Assert.AreNotSame(newInts[0], newInts[1]);
470    }
471
472    [TestMethod]
473    public void NonDefaultConstructorTest() {
474      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
475      try {
476        XmlGenerator.Serialize(c, tempFile);
477        Assert.Fail("Exception not thrown");
478      } catch (PersistenceException) {
479      }
480    }
481
482    [TestMethod]
483    public void TestSavingException() {
484      List<int> list = new List<int> { 1, 2, 3 };
485      XmlGenerator.Serialize(list, tempFile);
486      NonSerializable s = new NonSerializable();
487      try {
488        XmlGenerator.Serialize(s, tempFile);
489        Assert.Fail("Exception expected");
490      } catch (PersistenceException) { }
491      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
492      Assert.AreEqual(list[0], newList[0]);
493      Assert.AreEqual(list[1], newList[1]);
494    }
495
496    [TestMethod]
497    public void TestTypeStringConversion() {
498      string name = typeof(List<int>[]).AssemblyQualifiedName;
499      string shortName =
500        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
501      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
502      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
503      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
504    }
505
506    [TestMethod]
507    public void TestAssemblyVersionCheck() {
508      IntWrapper i = new IntWrapper(1);
509      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
510      XmlGenerator g = new XmlGenerator();
511      StringBuilder dataString = new StringBuilder();
512      foreach (var token in s) {
513        dataString.Append(g.Format(token));
514      }
515      StringBuilder typeString = new StringBuilder();
516      foreach (var line in g.Format(s.TypeCache))
517        typeString.Append(line);
518      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
519      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
520      IntWrapper newI = (IntWrapper)d.Deserialize(p);
521      Assert.AreEqual(i.Value, newI.Value);
522
523      string newTypeString = Regex.Replace(typeString.ToString(),
524        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
525        "Version=0.0.9999.9999");
526      try {
527        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
528        Assert.Fail("Exception expected");
529      } catch (PersistenceException x) {
530        Assert.IsTrue(x.Message.Contains("incompatible"));
531      }
532      newTypeString = Regex.Replace(typeString.ToString(),
533        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
534        "Version=$1.9999.9999");
535      try {
536        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
537        Assert.Fail("Exception expected");
538      } catch (PersistenceException x) {
539        Assert.IsTrue(x.Message.Contains("newer"));
540      }
541    }
542
543    [ClassInitialize]
544    public static void Initialize(TestContext testContext) {
545      ConfigurationService.Instance.Reset();
546    }
547  }
548}
Note: See TracBrowser for help on using the repository browser.