Free cookie consent management tool by TermsFeed Policy Generator

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

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

Implement missing primitive formatter for char and add more comprehensive tests. (#548)

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