Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceOverhaul/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCasesPersistenceNew.cs @ 13386

Last change on this file since 13386 was 13386, checked in by ascheibe, 8 years ago

#2520

  • fixed duplicate guids
  • adapted/added unit tests for new persistence
File size: 50.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Globalization;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30using System.Text;
31using System.Threading.Tasks;
32using HeuristicLab.Algorithms.GeneticAlgorithm;
33using HeuristicLab.Persistence;
34using HeuristicLab.Persistence.Auxiliary;
35using HeuristicLab.Persistence.Core;
36using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
37using HeuristicLab.Persistence.Default.DebugString;
38using HeuristicLab.Persistence.Default.Xml;
39using HeuristicLab.Persistence.Tests;
40using HeuristicLab.Tests;
41using Microsoft.VisualStudio.TestTools.UnitTesting;
42
43namespace HeuristicLab.PersistenceNew.Tests {
44  #region Test Classes
45  [StorableClass("7D9672BD-703D-42BB-9080-9929885D4580")]
46  public class NumberTest {
47    [Storable]
48    private bool _bool = true;
49    [Storable]
50    private byte _byte = 0xFF;
51    [Storable]
52    private sbyte _sbyte = 0xF;
53    [Storable]
54    private short _short = -123;
55    [Storable]
56    private ushort _ushort = 123;
57    [Storable]
58    private int _int = -123;
59    [Storable]
60    private uint _uint = 123;
61    [Storable]
62    private long _long = 123456;
63    [Storable]
64    private ulong _ulong = 123456;
65    public override bool Equals(object obj) {
66      NumberTest nt = obj as NumberTest;
67      if (nt == null)
68        throw new NotSupportedException();
69      return
70        nt._bool == _bool &&
71        nt._byte == _byte &&
72        nt._sbyte == _sbyte &&
73        nt._short == _short &&
74        nt._ushort == _ushort &&
75        nt._int == _int &&
76        nt._uint == _uint &&
77        nt._long == _long &&
78        nt._ulong == _ulong;
79    }
80    public override int GetHashCode() {
81      return
82        _bool.GetHashCode() ^
83        _byte.GetHashCode() ^
84        _sbyte.GetHashCode() ^
85        _short.GetHashCode() ^
86        _short.GetHashCode() ^
87        _int.GetHashCode() ^
88        _uint.GetHashCode() ^
89        _long.GetHashCode() ^
90        _ulong.GetHashCode();
91    }
92  }
93
94  [StorableClass("EEB19599-D5AC-48ED-A56B-CF213DFAF2E4")]
95  public class NonDefaultConstructorClass {
96    [Storable]
97    int value;
98    public NonDefaultConstructorClass(int value) {
99      this.value = value;
100    }
101  }
102
103  [StorableClass("EE43FE7A-6D07-4D52-9338-C21B3485F82A")]
104  public class IntWrapper {
105
106    [Storable]
107    public int Value;
108
109    private IntWrapper() { }
110
111    public IntWrapper(int value) {
112      this.Value = value;
113    }
114
115    public override bool Equals(object obj) {
116      if (obj as IntWrapper == null)
117        return false;
118      return Value.Equals(((IntWrapper)obj).Value);
119    }
120    public override int GetHashCode() {
121      return Value.GetHashCode();
122    }
123
124  }
125
126  [StorableClass("00A8E48E-8E8A-443C-A327-9F6ACCBE7E80")]
127  public class PrimitivesTest : NumberTest {
128    [Storable]
129    private char c = 'e';
130    [Storable]
131    private long[,] _long_array =
132      new long[,] { { 123, 456, }, { 789, 123 } };
133    [Storable]
134    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
135    [Storable]
136    private object o = new object();
137    public override bool Equals(object obj) {
138      PrimitivesTest pt = obj as PrimitivesTest;
139      if (pt == null)
140        throw new NotSupportedException();
141      return base.Equals(obj) &&
142        c == pt.c &&
143        _long_array == pt._long_array &&
144        list == pt.list &&
145        o == pt.o;
146    }
147    public override int GetHashCode() {
148      return base.GetHashCode() ^
149        c.GetHashCode() ^
150        _long_array.GetHashCode() ^
151        list.GetHashCode() ^
152        o.GetHashCode();
153    }
154  }
155
156  public enum TestEnum { va1, va2, va3, va8 } ;
157
158  [StorableClass("26BA37F6-926D-4665-A10A-1F39E1CF6468")]
159  public class RootBase {
160    [Storable]
161    private string baseString = "   Serial  ";
162    [Storable]
163    public TestEnum myEnum = TestEnum.va3;
164    public override bool Equals(object obj) {
165      RootBase rb = obj as RootBase;
166      if (rb == null)
167        throw new NotSupportedException();
168      return baseString == rb.baseString &&
169        myEnum == rb.myEnum;
170    }
171    public override int GetHashCode() {
172      return baseString.GetHashCode() ^
173        myEnum.GetHashCode();
174    }
175  }
176
177  [StorableClass("F6BCB436-B5F2-40F6-8E2F-7A018CD1CBA0")]
178  public class Root : RootBase {
179    [Storable]
180    public Stack<int> intStack = new Stack<int>();
181    [Storable]
182    public int[] i = new[] { 3, 4, 5, 6 };
183    [Storable(Name = "Test String")]
184    public string s;
185    [Storable]
186    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
187    [Storable]
188    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
189    [Storable]
190    public Custom c;
191    [Storable]
192    public List<Root> selfReferences;
193    [Storable]
194    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
195    [Storable]
196    public bool boolean = true;
197    [Storable]
198    public DateTime dateTime;
199    [Storable]
200    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
201    [Storable]
202    public Dictionary<string, int> dict = new Dictionary<string, int>();
203    [Storable(DefaultValue = "default")]
204    public string uninitialized;
205  }
206
207  public enum SimpleEnum { one, two, three }
208  public enum ComplexEnum { one = 1, two = 2, three = 3 }
209  [FlagsAttribute]
210  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
211
212  [StorableClass("2F6326ED-023A-415F-B5C7-9F9241940D05")]
213  public class EnumTest {
214    [Storable]
215    public SimpleEnum simpleEnum = SimpleEnum.one;
216    [Storable]
217    public ComplexEnum complexEnum = (ComplexEnum)2;
218    [Storable]
219    public TrickyEnum trickyEnum = (TrickyEnum)15;
220  }
221
222  [StorableClass("92365E2A-1184-4280-B763-4853C7ADF3E3")]
223  public class Custom {
224    [Storable]
225    public int i;
226    [Storable]
227    public Root r;
228    [Storable]
229    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
230  }
231
232  [StorableClass("7CF19EBC-1EC4-4FBE-BCA9-DA48E3CFE30D")]
233  public class Manager {
234
235    public DateTime lastLoadTime;
236    [Storable]
237    private DateTime lastLoadTimePersistence {
238      get { return lastLoadTime; }
239      set { lastLoadTime = DateTime.Now; }
240    }
241    [Storable]
242    public double? dbl;
243  }
244
245  [StorableClass("9092C705-F5E9-4BA9-9750-4357DB29AABF")]
246  public class C {
247    [Storable]
248    public C[][] allCs;
249    [Storable]
250    public KeyValuePair<List<C>, C> kvpList;
251  }
252
253  public class NonSerializable {
254    int x = 0;
255    public override bool Equals(object obj) {
256      NonSerializable ns = obj as NonSerializable;
257      if (ns == null)
258        throw new NotSupportedException();
259      return ns.x == x;
260    }
261    public override int GetHashCode() {
262      return x.GetHashCode();
263    }
264  }
265
266  #endregion
267
268  [TestClass]
269  public class UseCasesPersistenceNew {
270    #region Helpers
271    private string tempFile;
272
273    [ClassInitialize]
274    public static void Initialize(TestContext testContext) {
275      ConfigurationService.Instance.Reset();
276    }
277
278    [TestInitialize()]
279    public void CreateTempFile() {
280      tempFile = Path.GetTempFileName();
281    }
282
283    [TestCleanup()]
284    public void ClearTempFile() {
285      StreamReader reader = new StreamReader(tempFile);
286      string s = reader.ReadToEnd();
287      reader.Close();
288      File.Delete(tempFile);
289    }
290    #endregion
291
292    #region Persistence 4.0 test methods
293    [TestMethod]
294    [TestCategory("Persistence")]
295    [TestProperty("Time", "short")]
296    public void TestBool() {
297      bool test = true;
298      ProtoBufSerializer serializer = new ProtoBufSerializer();
299      serializer.Serialize(test, tempFile);
300      object o = serializer.Deserialize(tempFile);
301      bool result = (bool)o;
302      Assert.AreEqual(test, result);
303    }
304
305    [TestMethod]
306    [TestCategory("Persistence")]
307    [TestProperty("Time", "short")]
308    public void TestInt() {
309      int test = 42;
310      ProtoBufSerializer serializer = new ProtoBufSerializer();
311      serializer.Serialize(test, tempFile);
312      object o = serializer.Deserialize(tempFile);
313      int result = (int)o;
314      Assert.AreEqual(test, result);
315    }
316    #endregion
317
318
319    #region Old persistence test methods
320    [TestMethod]
321    [TestCategory("Persistence")]
322    [TestProperty("Time", "short")]
323    public void ComplexStorable() {
324      ProtoBufSerializer serializer = new ProtoBufSerializer();
325      Root r = InitializeComplexStorable();
326      serializer.Serialize(r, tempFile);
327      Root newR = (Root)serializer.Deserialize(tempFile);
328      CompareComplexStorables(r, newR);
329    }
330
331    private static void CompareComplexStorables(Root r, Root newR) {
332      Assert.AreEqual(
333        DebugStringGenerator.Serialize(r),
334        DebugStringGenerator.Serialize(newR));
335      Assert.AreSame(newR, newR.selfReferences[0]);
336      Assert.AreNotSame(r, newR);
337      Assert.AreEqual(r.myEnum, TestEnum.va1);
338      Assert.AreEqual(r.i[0], 7);
339      Assert.AreEqual(r.i[1], 5);
340      Assert.AreEqual(r.i[2], 6);
341      Assert.AreEqual(r.s, "new value");
342      Assert.AreEqual(r.intArray[0], 3);
343      Assert.AreEqual(r.intArray[1], 2);
344      Assert.AreEqual(r.intArray[2], 1);
345      Assert.AreEqual(r.intList[0], 9);
346      Assert.AreEqual(r.intList[1], 8);
347      Assert.AreEqual(r.intList[2], 7);
348      Assert.AreEqual(r.multiDimArray[0, 0], 5);
349      Assert.AreEqual(r.multiDimArray[0, 1], 4);
350      Assert.AreEqual(r.multiDimArray[0, 2], 3);
351      Assert.AreEqual(r.multiDimArray[1, 0], 1);
352      Assert.AreEqual(r.multiDimArray[1, 1], 4);
353      Assert.AreEqual(r.multiDimArray[1, 2], 6);
354      Assert.IsFalse(r.boolean);
355      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
356      Assert.AreEqual(r.kvp.Key, "string key");
357      Assert.AreEqual(r.kvp.Value, 321);
358      Assert.IsNull(r.uninitialized);
359      Assert.AreEqual(newR.myEnum, TestEnum.va1);
360      Assert.AreEqual(newR.i[0], 7);
361      Assert.AreEqual(newR.i[1], 5);
362      Assert.AreEqual(newR.i[2], 6);
363      Assert.AreEqual(newR.s, "new value");
364      Assert.AreEqual(newR.intArray[0], 3);
365      Assert.AreEqual(newR.intArray[1], 2);
366      Assert.AreEqual(newR.intArray[2], 1);
367      Assert.AreEqual(newR.intList[0], 9);
368      Assert.AreEqual(newR.intList[1], 8);
369      Assert.AreEqual(newR.intList[2], 7);
370      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
371      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
372      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
373      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
374      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
375      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
376      Assert.AreEqual(newR.intStack.Pop(), 3);
377      Assert.AreEqual(newR.intStack.Pop(), 2);
378      Assert.AreEqual(newR.intStack.Pop(), 1);
379      Assert.IsFalse(newR.boolean);
380      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
381      Assert.AreEqual(newR.kvp.Key, "string key");
382      Assert.AreEqual(newR.kvp.Value, 321);
383      Assert.IsNull(newR.uninitialized);
384    }
385
386    private static Root InitializeComplexStorable() {
387      Root r = new Root();
388      r.intStack.Push(1);
389      r.intStack.Push(2);
390      r.intStack.Push(3);
391      r.selfReferences = new List<Root> { r, r };
392      r.c = new Custom { r = r };
393      r.dict.Add("one", 1);
394      r.dict.Add("two", 2);
395      r.dict.Add("three", 3);
396      r.myEnum = TestEnum.va1;
397      r.i = new[] { 7, 5, 6 };
398      r.s = "new value";
399      r.intArray = new ArrayList { 3, 2, 1 };
400      r.intList = new List<int> { 9, 8, 7 };
401      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
402      r.boolean = false;
403      r.dateTime = DateTime.Now;
404      r.kvp = new KeyValuePair<string, int>("string key", 321);
405      r.uninitialized = null;
406
407      return r;
408    }
409
410    [TestMethod]
411    [TestCategory("Persistence")]
412    [TestProperty("Time", "short")]
413    public void SelfReferences() {
414      ProtoBufSerializer serializer = new ProtoBufSerializer();
415      C c = new C();
416      C[][] cs = new C[2][];
417      cs[0] = new C[] { c };
418      cs[1] = new C[] { c };
419      c.allCs = cs;
420      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
421      serializer.Serialize(cs, tempFile);
422      object o = serializer.Deserialize(tempFile);
423      Assert.AreEqual(
424        DebugStringGenerator.Serialize(cs),
425        DebugStringGenerator.Serialize(o));
426      Assert.AreSame(c, c.allCs[0][0]);
427      Assert.AreSame(c, c.allCs[1][0]);
428      Assert.AreSame(c, c.kvpList.Key[0]);
429      Assert.AreSame(c, c.kvpList.Value);
430      C[][] newCs = (C[][])o;
431      C newC = newCs[0][0];
432      Assert.AreSame(newC, newC.allCs[0][0]);
433      Assert.AreSame(newC, newC.allCs[1][0]);
434      Assert.AreSame(newC, newC.kvpList.Key[0]);
435      Assert.AreSame(newC, newC.kvpList.Value);
436    }
437
438    [TestMethod]
439    [TestCategory("Persistence")]
440    [TestProperty("Time", "short")]
441    public void ArrayCreation() {
442      ProtoBufSerializer serializer = new ProtoBufSerializer();
443      ArrayList[] arrayListArray = new ArrayList[4];
444      arrayListArray[0] = new ArrayList();
445      arrayListArray[0].Add(arrayListArray);
446      arrayListArray[0].Add(arrayListArray);
447      arrayListArray[1] = new ArrayList();
448      arrayListArray[1].Add(arrayListArray);
449      arrayListArray[2] = new ArrayList();
450      arrayListArray[2].Add(arrayListArray);
451      arrayListArray[2].Add(arrayListArray);
452      Array a = Array.CreateInstance(
453                              typeof(object),
454                              new[] { 1, 2 }, new[] { 3, 4 });
455      arrayListArray[2].Add(a);
456      serializer.Serialize(arrayListArray, tempFile);
457      object o = serializer.Deserialize(tempFile);
458      Assert.AreEqual(
459        DebugStringGenerator.Serialize(arrayListArray),
460        DebugStringGenerator.Serialize(o));
461      ArrayList[] newArray = (ArrayList[])o;
462      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
463      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
464      Assert.AreSame(newArray, newArray[0][0]);
465      Assert.AreSame(newArray, newArray[2][1]);
466    }
467
468    [TestMethod]
469    [TestCategory("Persistence")]
470    [TestProperty("Time", "short")]
471    public void CustomSerializationProperty() {
472      ProtoBufSerializer serializer = new ProtoBufSerializer();
473      Manager m = new Manager();
474      serializer.Serialize(m, tempFile);
475      Manager newM = (Manager)serializer.Deserialize(tempFile);
476      Assert.AreNotEqual(
477        DebugStringGenerator.Serialize(m),
478        DebugStringGenerator.Serialize(newM));
479      Assert.AreEqual(m.dbl, newM.dbl);
480      Assert.AreEqual(m.lastLoadTime, new DateTime());
481      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
482      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
483    }
484
485    [TestMethod]
486    [TestCategory("Persistence")]
487    [TestProperty("Time", "short")]
488    public void Primitives() {
489      ProtoBufSerializer serializer = new ProtoBufSerializer();
490      PrimitivesTest sdt = new PrimitivesTest();
491      serializer.Serialize(sdt, tempFile);
492      object o = serializer.Deserialize(tempFile);
493      Assert.AreEqual(
494        DebugStringGenerator.Serialize(sdt),
495        DebugStringGenerator.Serialize(o));
496    }
497
498    [TestMethod]
499    [TestCategory("Persistence")]
500    [TestProperty("Time", "short")]
501    public void MultiDimensionalArray() {
502      ProtoBufSerializer serializer = new ProtoBufSerializer();
503      string[,] mDimString = new string[,] {
504        {"ora", "et", "labora"},
505        {"Beten", "und", "Arbeiten"}
506      };
507      serializer.Serialize(mDimString, tempFile);
508      object o = serializer.Deserialize(tempFile);
509      Assert.AreEqual(
510        DebugStringGenerator.Serialize(mDimString),
511        DebugStringGenerator.Serialize(o));
512    }
513
514    [StorableClass("87A331AF-14DC-48B3-B577-D49065743BE6")]
515    public class NestedType {
516      [Storable]
517      private string value = "value";
518      public override bool Equals(object obj) {
519        NestedType nt = obj as NestedType;
520        if (nt == null)
521          throw new NotSupportedException();
522        return nt.value == value;
523      }
524      public override int GetHashCode() {
525        return value.GetHashCode();
526      }
527    }
528
529    [TestMethod]
530    [TestCategory("Persistence")]
531    [TestProperty("Time", "short")]
532    public void NestedTypeTest() {
533      ProtoBufSerializer serializer = new ProtoBufSerializer();
534      NestedType t = new NestedType();
535      serializer.Serialize(t, tempFile);
536      object o = serializer.Deserialize(tempFile);
537      Assert.AreEqual(
538        DebugStringGenerator.Serialize(t),
539        DebugStringGenerator.Serialize(o));
540      Assert.IsTrue(t.Equals(o));
541    }
542
543
544    [TestMethod]
545    [TestCategory("Persistence")]
546    [TestProperty("Time", "short")]
547    public void SimpleArray() {
548      ProtoBufSerializer serializer = new ProtoBufSerializer();
549      string[] strings = { "ora", "et", "labora" };
550      serializer.Serialize(strings, tempFile);
551      object o = serializer.Deserialize(tempFile);
552      Assert.AreEqual(
553        DebugStringGenerator.Serialize(strings),
554        DebugStringGenerator.Serialize(o));
555    }
556
557    [TestMethod]
558    [TestCategory("Persistence")]
559    [TestProperty("Time", "short")]
560    public void PrimitiveRoot() {
561      ProtoBufSerializer serializer = new ProtoBufSerializer();
562      serializer.Serialize(12.3f, tempFile);
563      object o = serializer.Deserialize(tempFile);
564      Assert.AreEqual(
565        DebugStringGenerator.Serialize(12.3f),
566        DebugStringGenerator.Serialize(o));
567    }
568
569    private string formatFullMemberName(MemberInfo mi) {
570      return new StringBuilder()
571        .Append(mi.DeclaringType.Assembly.GetName().Name)
572        .Append(": ")
573        .Append(mi.DeclaringType.Namespace)
574        .Append('.')
575        .Append(mi.DeclaringType.Name)
576        .Append('.')
577        .Append(mi.Name).ToString();
578    }
579
580    public void CodingConventions() {
581      List<string> lowerCaseMethodNames = new List<string>();
582      List<string> lowerCaseProperties = new List<string>();
583      List<string> lowerCaseFields = new List<string>();
584      foreach (Assembly a in PluginLoader.Assemblies) {
585        if (!a.GetName().Name.StartsWith("HeuristicLab"))
586          continue;
587        foreach (Type t in a.GetTypes()) {
588          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
589            if (mi.DeclaringType.Name.StartsWith("<>"))
590              continue;
591            if (char.IsLower(mi.Name[0])) {
592              if (mi.MemberType == MemberTypes.Field)
593                lowerCaseFields.Add(formatFullMemberName(mi));
594              if (mi.MemberType == MemberTypes.Property)
595                lowerCaseProperties.Add(formatFullMemberName(mi));
596              if (mi.MemberType == MemberTypes.Method &&
597                !mi.Name.StartsWith("get_") &&
598                !mi.Name.StartsWith("set_") &&
599                !mi.Name.StartsWith("add_") &&
600                !mi.Name.StartsWith("remove_") &&
601                !mi.Name.StartsWith("op_"))
602                lowerCaseMethodNames.Add(formatFullMemberName(mi));
603            }
604          }
605        }
606      }
607      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
608      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
609      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
610    }
611
612    [TestMethod]
613    [TestCategory("Persistence")]
614    [TestProperty("Time", "short")]
615    public void Enums() {
616      ProtoBufSerializer serializer = new ProtoBufSerializer();
617      EnumTest et = new EnumTest();
618      et.simpleEnum = SimpleEnum.two;
619      et.complexEnum = ComplexEnum.three;
620      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
621      serializer.Serialize(et, tempFile);
622      EnumTest newEt = (EnumTest)serializer.Deserialize(tempFile);
623      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
624      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
625      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
626    }
627
628    [TestMethod]
629    [TestCategory("Persistence")]
630    [TestProperty("Time", "short")]
631    public void TestAliasingWithOverriddenEquals() {
632      ProtoBufSerializer serializer = new ProtoBufSerializer();
633      List<IntWrapper> ints = new List<IntWrapper>();
634      ints.Add(new IntWrapper(1));
635      ints.Add(new IntWrapper(1));
636      Assert.AreEqual(ints[0], ints[1]);
637      Assert.AreNotSame(ints[0], ints[1]);
638      serializer.Serialize(ints, tempFile);
639      List<IntWrapper> newInts = (List<IntWrapper>)serializer.Deserialize(tempFile);
640      Assert.AreEqual(newInts[0].Value, 1);
641      Assert.AreEqual(newInts[1].Value, 1);
642      Assert.AreEqual(newInts[0], newInts[1]);
643      Assert.AreNotSame(newInts[0], newInts[1]);
644    }
645
646    [TestMethod]
647    [TestCategory("Persistence")]
648    [TestProperty("Time", "short")]
649    public void NonDefaultConstructorTest() {
650      ProtoBufSerializer serializer = new ProtoBufSerializer();
651      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
652      try {
653        serializer.Serialize(c, tempFile);
654        Assert.Fail("Exception not thrown");
655      }
656      catch (PersistenceException) {
657      }
658    }
659
660    [TestMethod]
661    [TestCategory("Persistence")]
662    [TestProperty("Time", "short")]
663    public void TestSavingException() {
664      ProtoBufSerializer serializer = new ProtoBufSerializer();
665      List<int> list = new List<int> { 1, 2, 3 };
666      serializer.Serialize(list, tempFile);
667      NonSerializable s = new NonSerializable();
668      try {
669        serializer.Serialize(s, tempFile);
670        Assert.Fail("Exception expected");
671      }
672      catch (PersistenceException) { }
673      List<int> newList = (List<int>)serializer.Deserialize(tempFile);
674      Assert.AreEqual(list[0], newList[0]);
675      Assert.AreEqual(list[1], newList[1]);
676    }
677
678    [TestMethod]
679    [TestCategory("Persistence")]
680    [TestProperty("Time", "short")]
681    public void TestTypeStringConversion() {
682      string name = typeof(List<int>[]).AssemblyQualifiedName;
683      string shortName =
684        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
685      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
686      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
687      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
688    }
689
690    [TestMethod]
691    [TestCategory("Persistence")]
692    [TestProperty("Time", "short")]
693    public void TestHexadecimalPublicKeyToken() {
694      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
695      string shortName = "TestClass, TestAssembly";
696      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
697      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
698    }
699
700    [TestMethod]
701    [TestCategory("Persistence")]
702    [TestProperty("Time", "short")]
703    public void InheritanceTest() {
704      ProtoBufSerializer serializer = new ProtoBufSerializer();
705      New n = new New();
706      serializer.Serialize(n, tempFile);
707      New nn = (New)serializer.Deserialize(tempFile);
708      Assert.AreEqual(n.Name, nn.Name);
709      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
710    }
711
712    [StorableClass("B963EF51-12B4-432E-8C54-88F026F9ACE2")]
713    class Child {
714      [Storable]
715      public GrandParent grandParent;
716    }
717
718    [StorableClass("E66E9606-967A-4C35-A361-F6F0D21C064A")]
719    class Parent {
720      [Storable]
721      public Child child;
722    }
723
724    [StorableClass("34D3893A-57AD-4F72-878B-81D6FA3F14A9")]
725    class GrandParent {
726      [Storable]
727      public Parent parent;
728    }
729
730    [TestMethod]
731    [TestCategory("Persistence")]
732    [TestProperty("Time", "short")]
733    public void InstantiateParentChainReference() {
734      ProtoBufSerializer serializer = new ProtoBufSerializer();
735      GrandParent gp = new GrandParent();
736      gp.parent = new Parent();
737      gp.parent.child = new Child();
738      gp.parent.child.grandParent = gp;
739      Assert.AreSame(gp, gp.parent.child.grandParent);
740      serializer.Serialize(gp, tempFile);
741      GrandParent newGp = (GrandParent)serializer.Deserialize(tempFile);
742      Assert.AreSame(newGp, newGp.parent.child.grandParent);
743    }
744
745    struct TestStruct {
746      int value;
747      int PropertyValue { get; set; }
748      public TestStruct(int value)
749        : this() {
750        this.value = value;
751        PropertyValue = value;
752      }
753    }
754
755    [TestMethod]
756    [TestCategory("Persistence")]
757    [TestProperty("Time", "short")]
758    public void StructTest() {
759      ProtoBufSerializer serializer = new ProtoBufSerializer();
760      TestStruct s = new TestStruct(10);
761      serializer.Serialize(s, tempFile);
762      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
763      Assert.AreEqual(s, newS);
764    }
765
766    [TestMethod]
767    [TestCategory("Persistence")]
768    [TestProperty("Time", "short")]
769    public void PointTest() {
770      ProtoBufSerializer serializer = new ProtoBufSerializer();
771      Point p = new Point(12, 34);
772      serializer.Serialize(p, tempFile);
773      Point newP = (Point)serializer.Deserialize(tempFile);
774      Assert.AreEqual(p, newP);
775    }
776
777    [TestMethod]
778    [TestCategory("Persistence")]
779    [TestProperty("Time", "short")]
780    public void NullableValueTypes() {
781      ProtoBufSerializer serializer = new ProtoBufSerializer();
782      double?[] d = new double?[] { null, 1, 2, 3 };
783      serializer.Serialize(d, tempFile);
784      double?[] newD = (double?[])serializer.Deserialize(tempFile);
785      Assert.AreEqual(d[0], newD[0]);
786      Assert.AreEqual(d[1], newD[1]);
787      Assert.AreEqual(d[2], newD[2]);
788      Assert.AreEqual(d[3], newD[3]);
789    }
790
791    [TestMethod]
792    [TestCategory("Persistence")]
793    [TestProperty("Time", "short")]
794    public void BitmapTest() {
795      ProtoBufSerializer serializer = new ProtoBufSerializer();
796      Icon icon = System.Drawing.SystemIcons.Hand;
797      Bitmap bitmap = icon.ToBitmap();
798      serializer.Serialize(bitmap, tempFile);
799      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
800
801      Assert.AreEqual(bitmap.Size, newBitmap.Size);
802      for (int i = 0; i < bitmap.Size.Width; i++)
803        for (int j = 0; j < bitmap.Size.Height; j++)
804          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
805    }
806
807    [StorableClass("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
808    private class PersistenceHooks {
809      [Storable]
810      public int a;
811      [Storable]
812      public int b;
813      public int sum;
814      public bool WasSerialized { get; private set; }
815      [StorableHook(HookType.BeforeSerialization)]
816      void PreSerializationHook() {
817        WasSerialized = true;
818      }
819      [StorableHook(HookType.AfterDeserialization)]
820      void PostDeserializationHook() {
821        sum = a + b;
822      }
823    }
824
825    [TestMethod]
826    [TestCategory("Persistence")]
827    [TestProperty("Time", "short")]
828    public void HookTest() {
829      ProtoBufSerializer serializer = new ProtoBufSerializer();
830      PersistenceHooks hookTest = new PersistenceHooks();
831      hookTest.a = 2;
832      hookTest.b = 5;
833      Assert.IsFalse(hookTest.WasSerialized);
834      Assert.AreEqual(hookTest.sum, 0);
835      serializer.Serialize(hookTest, tempFile);
836      Assert.IsTrue(hookTest.WasSerialized);
837      Assert.AreEqual(hookTest.sum, 0);
838      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
839      Assert.AreEqual(newHookTest.a, hookTest.a);
840      Assert.AreEqual(newHookTest.b, hookTest.b);
841      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
842      Assert.IsFalse(newHookTest.WasSerialized);
843    }
844
845    [StorableClass("A35D71DF-397F-4910-A950-ED6923BE9483")]
846    private class CustomConstructor {
847      public string Value = "none";
848      public CustomConstructor() {
849        Value = "default";
850      }
851      [StorableConstructor]
852      private CustomConstructor(bool deserializing) {
853        Assert.IsTrue(deserializing);
854        Value = "persistence";
855      }
856    }
857
858    [TestMethod]
859    [TestCategory("Persistence")]
860    [TestProperty("Time", "short")]
861    public void TestCustomConstructor() {
862      ProtoBufSerializer serializer = new ProtoBufSerializer();
863      CustomConstructor cc = new CustomConstructor();
864      Assert.AreEqual(cc.Value, "default");
865      serializer.Serialize(cc, tempFile);
866      CustomConstructor newCC = (CustomConstructor)serializer.Deserialize(tempFile);
867      Assert.AreEqual(newCC.Value, "persistence");
868    }
869
870    [StorableClass("D276E825-1F35-4BAC-8937-9ABC91D5C316")]
871    public class ExplodingDefaultConstructor {
872      public ExplodingDefaultConstructor() {
873        throw new Exception("this constructor will always fail");
874      }
875      public ExplodingDefaultConstructor(string password) {
876      }
877    }
878
879    [TestMethod]
880    [TestCategory("Persistence")]
881    [TestProperty("Time", "short")]
882    public void TestConstructorExceptionUnwrapping() {
883      ProtoBufSerializer serializer = new ProtoBufSerializer();
884      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
885      serializer.Serialize(x, tempFile);
886      try {
887        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)serializer.Deserialize(tempFile);
888        Assert.Fail("Exception expected");
889      }
890      catch (PersistenceException pe) {
891        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
892      }
893    }
894
895    [TestMethod]
896    [TestCategory("Persistence")]
897    [TestProperty("Time", "short")]
898    public void TestRejectionJustifications() {
899      ProtoBufSerializer serializer = new ProtoBufSerializer();
900      NonSerializable ns = new NonSerializable();
901      try {
902        serializer.Serialize(ns, tempFile);
903        Assert.Fail("PersistenceException expected");
904      }
905      catch (PersistenceException x) {
906        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
907      }
908    }
909
910    [TestMethod]
911    [TestCategory("Persistence")]
912    [TestProperty("Time", "short")]
913    public void TestStreaming() {
914      ProtoBufSerializer serializer = new ProtoBufSerializer();
915      using (MemoryStream stream = new MemoryStream()) {
916        Root r = InitializeComplexStorable();
917        serializer.Serialize(r, stream);
918        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
919          Root newR = (Root)serializer.Deserialize(stream2);
920          CompareComplexStorables(r, newR);
921        }
922      }
923    }
924
925    [StorableClass("4921031B-CB61-4677-97AD-9236A4CEC200")]
926    public class HookInheritanceTestBase {
927      [Storable]
928      public object a;
929      public object link;
930      [StorableHook(HookType.AfterDeserialization)]
931      private void relink() {
932        link = a;
933      }
934    }
935
936    [StorableClass("321CEE0A-5201-4CE2-B135-2343890D96BF")]
937    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
938      [Storable]
939      public object b;
940      [StorableHook(HookType.AfterDeserialization)]
941      private void relink() {
942        Assert.AreSame(a, link);
943        link = b;
944      }
945    }
946
947    [TestMethod]
948    [TestCategory("Persistence")]
949    [TestProperty("Time", "short")]
950    public void TestLinkInheritance() {
951      ProtoBufSerializer serializer = new ProtoBufSerializer();
952      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
953      c.a = new object();
954      serializer.Serialize(c, tempFile);
955      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)serializer.Deserialize(tempFile);
956      Assert.AreSame(c.b, c.link);
957    }
958
959    [StorableClass(StorableClassType.AllFields, "B9AB42E8-1932-425B-B4CF-F31F07EAC599")]
960    public class AllFieldsStorable {
961      public int Value1 = 1;
962      [Storable]
963      public int Value2 = 2;
964      public int Value3 { get; private set; }
965      public int Value4 { get; private set; }
966      [StorableConstructor]
967      public AllFieldsStorable(bool isDeserializing) {
968        if (!isDeserializing) {
969          Value1 = 12;
970          Value2 = 23;
971          Value3 = 34;
972          Value4 = 56;
973        }
974      }
975    }
976
977    [TestMethod]
978    [TestCategory("Persistence")]
979    [TestProperty("Time", "short")]
980    public void TestStorableClassDiscoveryAllFields() {
981      ProtoBufSerializer serializer = new ProtoBufSerializer();
982      AllFieldsStorable afs = new AllFieldsStorable(false);
983      serializer.Serialize(afs, tempFile);
984      AllFieldsStorable newAfs = (AllFieldsStorable)serializer.Deserialize(tempFile);
985      Assert.AreEqual(afs.Value1, newAfs.Value1);
986      Assert.AreEqual(afs.Value2, newAfs.Value2);
987      Assert.AreEqual(0, newAfs.Value3);
988      Assert.AreEqual(0, newAfs.Value4);
989    }
990
991    [StorableClass(StorableClassType.AllProperties, "CB7DC31C-AEF3-4EB8-91CA-248B767E9F92")]
992    public class AllPropertiesStorable {
993      public int Value1 = 1;
994      [Storable]
995      public int Value2 = 2;
996      public int Value3 { get; private set; }
997      public int Value4 { get; private set; }
998      [StorableConstructor]
999      public AllPropertiesStorable(bool isDeserializing) {
1000        if (!isDeserializing) {
1001          Value1 = 12;
1002          Value2 = 23;
1003          Value3 = 34;
1004          Value4 = 56;
1005        }
1006      }
1007    }
1008
1009    [TestMethod]
1010    [TestCategory("Persistence")]
1011    [TestProperty("Time", "short")]
1012    public void TestStorableClassDiscoveryAllProperties() {
1013      ProtoBufSerializer serializer = new ProtoBufSerializer();
1014      AllPropertiesStorable afs = new AllPropertiesStorable(false);
1015      serializer.Serialize(afs, tempFile);
1016      AllPropertiesStorable newAfs = (AllPropertiesStorable)serializer.Deserialize(tempFile);
1017      Assert.AreEqual(1, newAfs.Value1);
1018      Assert.AreEqual(2, newAfs.Value2);
1019      Assert.AreEqual(afs.Value3, newAfs.Value3);
1020      Assert.AreEqual(afs.Value4, newAfs.Value4);
1021
1022    }
1023
1024    [StorableClass(StorableClassType.AllFieldsAndAllProperties, "0AD8D68F-E0FF-4FA8-8A72-1148CD91A2B9")]
1025    public class AllFieldsAndAllPropertiesStorable {
1026      public int Value1 = 1;
1027      [Storable]
1028      public int Value2 = 2;
1029      public int Value3 { get; private set; }
1030      public int Value4 { get; private set; }
1031      [StorableConstructor]
1032      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1033        if (!isDeserializing) {
1034          Value1 = 12;
1035          Value2 = 23;
1036          Value3 = 34;
1037          Value4 = 56;
1038        }
1039      }
1040    }
1041
1042    [TestMethod]
1043    [TestCategory("Persistence")]
1044    [TestProperty("Time", "short")]
1045    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1046      ProtoBufSerializer serializer = new ProtoBufSerializer();
1047      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1048      serializer.Serialize(afs, tempFile);
1049      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)serializer.Deserialize(tempFile);
1050      Assert.AreEqual(afs.Value1, newAfs.Value1);
1051      Assert.AreEqual(afs.Value2, newAfs.Value2);
1052      Assert.AreEqual(afs.Value3, newAfs.Value3);
1053      Assert.AreEqual(afs.Value4, newAfs.Value4);
1054    }
1055
1056    [StorableClass(StorableClassType.MarkedOnly, "0D94E6D4-64E3-4637-B1EE-DEF2B3F6E2E0")]
1057    public class MarkedOnlyStorable {
1058      public int Value1 = 1;
1059      [Storable]
1060      public int Value2 = 2;
1061      public int Value3 { get; private set; }
1062      public int Value4 { get; private set; }
1063      [StorableConstructor]
1064      public MarkedOnlyStorable(bool isDeserializing) {
1065        if (!isDeserializing) {
1066          Value1 = 12;
1067          Value2 = 23;
1068          Value3 = 34;
1069          Value4 = 56;
1070        }
1071      }
1072    }
1073
1074    [TestMethod]
1075    [TestCategory("Persistence")]
1076    [TestProperty("Time", "short")]
1077    public void TestStorableClassDiscoveryMarkedOnly() {
1078      ProtoBufSerializer serializer = new ProtoBufSerializer();
1079      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1080      serializer.Serialize(afs, tempFile);
1081      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)serializer.Deserialize(tempFile);
1082      Assert.AreEqual(1, newAfs.Value1);
1083      Assert.AreEqual(afs.Value2, newAfs.Value2);
1084      Assert.AreEqual(0, newAfs.Value3);
1085      Assert.AreEqual(0, newAfs.Value4);
1086    }
1087
1088    [TestMethod]
1089    [TestCategory("Persistence")]
1090    [TestProperty("Time", "short")]
1091    public void TestLineEndings() {
1092      ProtoBufSerializer serializer = new ProtoBufSerializer();
1093      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1094      List<string> lines = new List<string>();
1095      foreach (var br in lineBreaks)
1096        lines.Add("line1" + br + "line2");
1097      serializer.Serialize(lines, tempFile);
1098      List<string> newLines = (List<string>)serializer.Deserialize(tempFile);
1099      Assert.AreEqual(lines.Count, newLines.Count);
1100      for (int i = 0; i < lineBreaks.Count; i++) {
1101        Assert.AreEqual(lines[i], newLines[i]);
1102      }
1103    }
1104
1105    [TestMethod]
1106    [TestCategory("Persistence")]
1107    [TestProperty("Time", "short")]
1108    public void TestSpecialNumbers() {
1109      ProtoBufSerializer serializer = new ProtoBufSerializer();
1110      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1111      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1112      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1113      Assert.IsTrue(double.IsNaN(specials[2]));
1114      serializer.Serialize(specials, tempFile);
1115      List<double> newSpecials = (List<double>)serializer.Deserialize(tempFile);
1116      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1117      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1118      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1119    }
1120
1121    [TestMethod]
1122    [TestCategory("Persistence")]
1123    [TestProperty("Time", "short")]
1124    public void TestStringSplit() {
1125      string s = "1.2;2.3;3.4;;;4.9";
1126      var l = s.EnumerateSplit(';').ToList();
1127      Assert.AreEqual("1.2", l[0]);
1128      Assert.AreEqual("2.3", l[1]);
1129      Assert.AreEqual("3.4", l[2]);
1130      Assert.AreEqual("4.9", l[3]);
1131    }
1132
1133    private class IdentityComparer<T> : IEqualityComparer<T> {
1134
1135      public bool Equals(T x, T y) {
1136        return x.Equals(y);
1137      }
1138
1139      public int GetHashCode(T obj) {
1140        return obj.GetHashCode();
1141      }
1142    }
1143
1144    [TestMethod]
1145    [TestCategory("Persistence")]
1146    [TestProperty("Time", "short")]
1147    public void TestHashSetSerializer() {
1148      ProtoBufSerializer serializer = new ProtoBufSerializer();
1149      var hashSets = new List<HashSet<int>>() {
1150        new HashSet<int>(new[] { 1, 2, 3 }),
1151        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1152      };
1153      serializer.Serialize(hashSets, tempFile);
1154      var newHashSets = (List<HashSet<int>>)serializer.Deserialize(tempFile);
1155      Assert.IsTrue(newHashSets[0].Contains(1));
1156      Assert.IsTrue(newHashSets[0].Contains(2));
1157      Assert.IsTrue(newHashSets[0].Contains(3));
1158      Assert.IsTrue(newHashSets[1].Contains(4));
1159      Assert.IsTrue(newHashSets[1].Contains(5));
1160      Assert.IsTrue(newHashSets[1].Contains(6));
1161      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1162      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1163    }
1164
1165    [TestMethod]
1166    [TestCategory("Persistence")]
1167    [TestProperty("Time", "short")]
1168    public void TestConcreteDictionarySerializer() {
1169      ProtoBufSerializer serializer = new ProtoBufSerializer();
1170      var dictionaries = new List<Dictionary<int, int>>() {
1171        new Dictionary<int, int>(),
1172        new Dictionary<int, int>(new IdentityComparer<int>()),
1173      };
1174      dictionaries[0].Add(1, 1);
1175      dictionaries[0].Add(2, 2);
1176      dictionaries[0].Add(3, 3);
1177      dictionaries[1].Add(4, 4);
1178      dictionaries[1].Add(5, 5);
1179      dictionaries[1].Add(6, 6);
1180      serializer.Serialize(dictionaries, tempFile);
1181      var newDictionaries = (List<Dictionary<int, int>>)serializer.Deserialize(tempFile);
1182      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1183      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1184      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1185      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1186      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1187      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1188      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1189      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1190      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1191      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1192      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1193      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1194      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1195      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1196    }
1197
1198    [StorableClass("A9B0D7FB-0CAF-4DD7-9045-EA136F9176F7")]
1199    public class ReadOnlyFail {
1200      [Storable]
1201      public string ReadOnly {
1202        get { return "fail"; }
1203      }
1204    }
1205
1206    [TestMethod]
1207    [TestCategory("Persistence")]
1208    [TestProperty("Time", "short")]
1209    public void TestReadOnlyFail() {
1210      ProtoBufSerializer serializer = new ProtoBufSerializer();
1211      try {
1212        serializer.Serialize(new ReadOnlyFail(), tempFile);
1213        Assert.Fail("Exception expected");
1214      }
1215      catch (PersistenceException) {
1216      }
1217      catch {
1218        Assert.Fail("PersistenceException expected");
1219      }
1220    }
1221
1222
1223    [StorableClass("2C9CC576-6823-4784-817B-37C8AF0B1C29")]
1224    public class WriteOnlyFail {
1225      [Storable]
1226      public string WriteOnly {
1227        set { throw new InvalidOperationException("this property should never be set."); }
1228      }
1229    }
1230
1231    [TestMethod]
1232    [TestCategory("Persistence")]
1233    [TestProperty("Time", "short")]
1234    public void TestWriteOnlyFail() {
1235      ProtoBufSerializer serializer = new ProtoBufSerializer();
1236      try {
1237        serializer.Serialize(new WriteOnlyFail(), tempFile);
1238        Assert.Fail("Exception expected");
1239      }
1240      catch (PersistenceException) {
1241      }
1242      catch {
1243        Assert.Fail("PersistenceException expected.");
1244      }
1245    }
1246
1247    [StorableClass("8052D9E3-6DDD-4AE1-9B5B-67C6D5436512")]
1248    public class OneWayTest {
1249      public OneWayTest() { this.value = "default"; }
1250      public string value;
1251      [Storable(AllowOneWay = true)]
1252      public string ReadOnly {
1253        get { return "ReadOnly"; }
1254      }
1255      [Storable(AllowOneWay = true)]
1256      public string WriteOnly {
1257        set { this.value = value; }
1258      }
1259    }
1260
1261    //TODO
1262    /* [TestMethod]
1263     [TestCategory("Persistence")]
1264     [TestProperty("Time", "short")]
1265     public void TestTypeCacheExport() {
1266       ProtoBufSerializer serializer = new ProtoBufSerializer();
1267       var test = new List<List<int>>();
1268       test.Add(new List<int>() { 1, 2, 3 });
1269       IEnumerable<Type> types;
1270       using (var stream = new MemoryStream()) {
1271         XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1272       }
1273       List<Type> t = new List<Type>(types);
1274       // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1275       Assert.IsTrue(t.Contains(typeof(List<int>)));
1276       Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1277       Assert.AreEqual(t.Count, 2);
1278     }*/
1279
1280    [TestMethod]
1281    [TestCategory("Persistence")]
1282    [TestProperty("Time", "short")]
1283    public void TupleTest() {
1284      var t1 = Tuple.Create(1);
1285      var t2 = Tuple.Create('1', "2");
1286      var t3 = Tuple.Create(3.0, 3f, 5);
1287      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1288      var tuple = Tuple.Create(t1, t2, t3, t4);
1289      XmlGenerator.Serialize(tuple, tempFile);
1290      var newTuple = XmlParser.Deserialize<Tuple<Tuple<int>, Tuple<char, string>, Tuple<double, float, int>, Tuple<Tuple<int, int, int>, Tuple<int, int, int>, Tuple<int, int, int>>>>(tempFile);
1291      Assert.AreEqual(tuple, newTuple);
1292    }
1293
1294    [TestMethod]
1295    [TestCategory("Persistence")]
1296    [TestProperty("Time", "short")]
1297    public void FontTest() {
1298      ProtoBufSerializer serializer = new ProtoBufSerializer();
1299      List<Font> fonts = new List<Font>() {
1300        new Font(FontFamily.GenericSansSerif, 12),
1301        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1302        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1303        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1304      };
1305      serializer.Serialize(fonts, tempFile);
1306      var newFonts = (List<Font>)serializer.Deserialize(tempFile);
1307      Assert.AreEqual(fonts[0], newFonts[0]);
1308      Assert.AreEqual(fonts[1], newFonts[1]);
1309      Assert.AreEqual(fonts[2], newFonts[2]);
1310      Assert.AreEqual(fonts[3], newFonts[3]);
1311    }
1312
1313    [TestMethod]
1314    [TestCategory("Persistence")]
1315    [TestProperty("Time", "medium")]
1316    public void ConcurrencyTest() {
1317      ProtoBufSerializer serializer = new ProtoBufSerializer();
1318      int n = 20;
1319      Task[] tasks = new Task[n];
1320      for (int i = 0; i < n; i++) {
1321        tasks[i] = Task.Factory.StartNew((idx) => {
1322          byte[] data;
1323          using (var stream = new MemoryStream()) {
1324            serializer.Serialize(new GeneticAlgorithm(), stream);
1325            data = stream.ToArray();
1326          }
1327        }, i);
1328      }
1329      Task.WaitAll(tasks);
1330    }
1331
1332    [TestMethod]
1333    [TestCategory("Persistence")]
1334    [TestProperty("Time", "medium")]
1335    public void ConcurrentBitmapTest() {
1336      ProtoBufSerializer serializer = new ProtoBufSerializer();
1337      Bitmap b = new Bitmap(300, 300);
1338      System.Random r = new System.Random();
1339      for (int x = 0; x < b.Height; x++) {
1340        for (int y = 0; y < b.Width; y++) {
1341          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1342        }
1343      }
1344      Task[] tasks = new Task[20];
1345      byte[][] datas = new byte[tasks.Length][];
1346      for (int i = 0; i < tasks.Length; i++) {
1347        tasks[i] = Task.Factory.StartNew((idx) => {
1348          using (var stream = new MemoryStream()) {
1349            serializer.Serialize(b, stream);
1350            datas[(int)idx] = stream.ToArray();
1351          }
1352        }, i);
1353      }
1354      Task.WaitAll(tasks);
1355    }
1356
1357    public class G<T, T2> {
1358      public class S { }
1359      public class S2<T3, T4> { }
1360    }
1361
1362
1363    [TestMethod]
1364    [TestCategory("Persistence")]
1365    [TestProperty("Time", "short")]
1366    public void TestSpecialCharacters() {
1367      ProtoBufSerializer serializer = new ProtoBufSerializer();
1368      var s = "abc" + "\x15" + "def";
1369      serializer.Serialize(s, tempFile);
1370      var newS = serializer.Deserialize(tempFile);
1371      Assert.AreEqual(s, newS);
1372    }
1373
1374    [TestMethod]
1375    [TestCategory("Persistence")]
1376    [TestProperty("Time", "short")]
1377    public void TestByteArray() {
1378      ProtoBufSerializer serializer = new ProtoBufSerializer();
1379      var b = new byte[3];
1380      b[0] = 0;
1381      b[1] = 200;
1382      b[2] = byte.MaxValue;
1383      serializer.Serialize(b, tempFile);
1384      var newB = (byte[])serializer.Deserialize(tempFile);
1385      CollectionAssert.AreEqual(b, newB);
1386    }
1387
1388    [TestMethod]
1389    [TestCategory("Persistence")]
1390    [TestProperty("Time", "short")]
1391    public void TestOptionalNumberEnumerable() {
1392      ProtoBufSerializer serializer = new ProtoBufSerializer();
1393      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
1394      serializer.Serialize(values, tempFile);
1395      var newValues = (List<double?>)serializer.Deserialize(tempFile);
1396      CollectionAssert.AreEqual(values, newValues);
1397    }
1398
1399    [TestMethod]
1400    [TestCategory("Persistence")]
1401    [TestProperty("Time", "short")]
1402    public void TestOptionalDateTimeEnumerable() {
1403      ProtoBufSerializer serializer = new ProtoBufSerializer();
1404      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
1405        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
1406      serializer.Serialize(values, tempFile);
1407      var newValues = (List<DateTime?>)serializer.Deserialize(tempFile);
1408      CollectionAssert.AreEqual(values, newValues);
1409    }
1410
1411    [TestMethod]
1412    [TestCategory("Persistence")]
1413    [TestProperty("Time", "short")]
1414    public void TestStringEnumerable() {
1415      ProtoBufSerializer serializer = new ProtoBufSerializer();
1416      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
1417      serializer.Serialize(values, tempFile);
1418      var newValues = (List<String>)serializer.Deserialize(tempFile);
1419      CollectionAssert.AreEqual(values, newValues);
1420    }
1421
1422    [TestMethod]
1423    [TestCategory("Persistence")]
1424    [TestProperty("Time", "short")]
1425    public void TestUnicodeCharArray() {
1426      ProtoBufSerializer serializer = new ProtoBufSerializer();
1427      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1428      serializer.Serialize(s, tempFile);
1429      var newS = (char[])serializer.Deserialize(tempFile);
1430      CollectionAssert.AreEqual(s, newS);
1431    }
1432
1433    [TestMethod]
1434    [TestCategory("Persistence")]
1435    [TestProperty("Time", "short")]
1436    public void TestUnicode() {
1437      ProtoBufSerializer serializer = new ProtoBufSerializer();
1438      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1439      serializer.Serialize(s, tempFile);
1440      var newS = serializer.Deserialize(tempFile);
1441      Assert.AreEqual(s, newS);
1442    }
1443
1444    [TestMethod]
1445    [TestCategory("Persistence")]
1446    [TestProperty("Time", "short")]
1447    public void TestQueue() {
1448      ProtoBufSerializer serializer = new ProtoBufSerializer();
1449      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
1450      serializer.Serialize(q, tempFile);
1451      var newQ = (Queue<int>)serializer.Deserialize(tempFile);
1452      CollectionAssert.AreEqual(q, newQ);
1453    }
1454    #endregion
1455  }
1456}
Note: See TracBrowser for help on using the repository browser.