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

Last change on this file since 13407 was 13407, checked in by ascheibe, 7 years ago

#2520 worked on type and enum transformers

File size: 52.2 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
317    [TestMethod]
318    [TestCategory("Persistence")]
319    [TestProperty("Time", "short")]
320    public void TestEnumSimple() {
321      SimpleEnum se = SimpleEnum.two;
322      ComplexEnum ce = ComplexEnum.three;
323      ProtoBufSerializer serializer = new ProtoBufSerializer();
324      serializer.Serialize(se, tempFile);
325      object o = serializer.Deserialize(tempFile);
326      SimpleEnum result = (SimpleEnum)o;
327      Assert.AreEqual(se, result);
328    }
329
330    [TestMethod]
331    [TestCategory("Persistence")]
332    [TestProperty("Time", "short")]
333    public void TestEnumComplex() {
334      ComplexEnum ce = ComplexEnum.three;
335      ProtoBufSerializer serializer = new ProtoBufSerializer();
336      serializer.Serialize(ce, tempFile);
337      object o = serializer.Deserialize(tempFile);
338      ComplexEnum result = (ComplexEnum)o;
339      Assert.AreEqual(ce, result);
340    }
341
342    [TestMethod]
343    [TestCategory("Persistence")]
344    [TestProperty("Time", "short")]
345    public void TestType() {
346      Type test = typeof(HeuristicLab.Algorithms.GeneticAlgorithm.GeneticAlgorithm);
347      ProtoBufSerializer serializer = new ProtoBufSerializer();
348      serializer.Serialize(test, tempFile);
349      object o = serializer.Deserialize(tempFile);
350      Type result = (Type)o;
351      Assert.AreEqual(test, result);
352    }
353
354    #endregion
355
356
357    #region Old persistence test methods
358    [TestMethod]
359    [TestCategory("Persistence")]
360    [TestProperty("Time", "short")]
361    public void ComplexStorable() {
362      ProtoBufSerializer serializer = new ProtoBufSerializer();
363      Root r = InitializeComplexStorable();
364      serializer.Serialize(r, tempFile);
365      Root newR = (Root)serializer.Deserialize(tempFile);
366      CompareComplexStorables(r, newR);
367    }
368
369    private static void CompareComplexStorables(Root r, Root newR) {
370      Assert.AreEqual(
371        DebugStringGenerator.Serialize(r),
372        DebugStringGenerator.Serialize(newR));
373      Assert.AreSame(newR, newR.selfReferences[0]);
374      Assert.AreNotSame(r, newR);
375      Assert.AreEqual(r.myEnum, TestEnum.va1);
376      Assert.AreEqual(r.i[0], 7);
377      Assert.AreEqual(r.i[1], 5);
378      Assert.AreEqual(r.i[2], 6);
379      Assert.AreEqual(r.s, "new value");
380      Assert.AreEqual(r.intArray[0], 3);
381      Assert.AreEqual(r.intArray[1], 2);
382      Assert.AreEqual(r.intArray[2], 1);
383      Assert.AreEqual(r.intList[0], 9);
384      Assert.AreEqual(r.intList[1], 8);
385      Assert.AreEqual(r.intList[2], 7);
386      Assert.AreEqual(r.multiDimArray[0, 0], 5);
387      Assert.AreEqual(r.multiDimArray[0, 1], 4);
388      Assert.AreEqual(r.multiDimArray[0, 2], 3);
389      Assert.AreEqual(r.multiDimArray[1, 0], 1);
390      Assert.AreEqual(r.multiDimArray[1, 1], 4);
391      Assert.AreEqual(r.multiDimArray[1, 2], 6);
392      Assert.IsFalse(r.boolean);
393      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
394      Assert.AreEqual(r.kvp.Key, "string key");
395      Assert.AreEqual(r.kvp.Value, 321);
396      Assert.IsNull(r.uninitialized);
397      Assert.AreEqual(newR.myEnum, TestEnum.va1);
398      Assert.AreEqual(newR.i[0], 7);
399      Assert.AreEqual(newR.i[1], 5);
400      Assert.AreEqual(newR.i[2], 6);
401      Assert.AreEqual(newR.s, "new value");
402      Assert.AreEqual(newR.intArray[0], 3);
403      Assert.AreEqual(newR.intArray[1], 2);
404      Assert.AreEqual(newR.intArray[2], 1);
405      Assert.AreEqual(newR.intList[0], 9);
406      Assert.AreEqual(newR.intList[1], 8);
407      Assert.AreEqual(newR.intList[2], 7);
408      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
409      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
410      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
411      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
412      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
413      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
414      Assert.AreEqual(newR.intStack.Pop(), 3);
415      Assert.AreEqual(newR.intStack.Pop(), 2);
416      Assert.AreEqual(newR.intStack.Pop(), 1);
417      Assert.IsFalse(newR.boolean);
418      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
419      Assert.AreEqual(newR.kvp.Key, "string key");
420      Assert.AreEqual(newR.kvp.Value, 321);
421      Assert.IsNull(newR.uninitialized);
422    }
423
424    private static Root InitializeComplexStorable() {
425      Root r = new Root();
426      r.intStack.Push(1);
427      r.intStack.Push(2);
428      r.intStack.Push(3);
429      r.selfReferences = new List<Root> { r, r };
430      r.c = new Custom { r = r };
431      r.dict.Add("one", 1);
432      r.dict.Add("two", 2);
433      r.dict.Add("three", 3);
434      r.myEnum = TestEnum.va1;
435      r.i = new[] { 7, 5, 6 };
436      r.s = "new value";
437      r.intArray = new ArrayList { 3, 2, 1 };
438      r.intList = new List<int> { 9, 8, 7 };
439      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
440      r.boolean = false;
441      r.dateTime = DateTime.Now;
442      r.kvp = new KeyValuePair<string, int>("string key", 321);
443      r.uninitialized = null;
444
445      return r;
446    }
447
448    [TestMethod]
449    [TestCategory("Persistence")]
450    [TestProperty("Time", "short")]
451    public void SelfReferences() {
452      ProtoBufSerializer serializer = new ProtoBufSerializer();
453      C c = new C();
454      C[][] cs = new C[2][];
455      cs[0] = new C[] { c };
456      cs[1] = new C[] { c };
457      c.allCs = cs;
458      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
459      serializer.Serialize(cs, tempFile);
460      object o = serializer.Deserialize(tempFile);
461      Assert.AreEqual(
462        DebugStringGenerator.Serialize(cs),
463        DebugStringGenerator.Serialize(o));
464      Assert.AreSame(c, c.allCs[0][0]);
465      Assert.AreSame(c, c.allCs[1][0]);
466      Assert.AreSame(c, c.kvpList.Key[0]);
467      Assert.AreSame(c, c.kvpList.Value);
468      C[][] newCs = (C[][])o;
469      C newC = newCs[0][0];
470      Assert.AreSame(newC, newC.allCs[0][0]);
471      Assert.AreSame(newC, newC.allCs[1][0]);
472      Assert.AreSame(newC, newC.kvpList.Key[0]);
473      Assert.AreSame(newC, newC.kvpList.Value);
474    }
475
476    [TestMethod]
477    [TestCategory("Persistence")]
478    [TestProperty("Time", "short")]
479    public void ArrayCreation() {
480      ProtoBufSerializer serializer = new ProtoBufSerializer();
481      ArrayList[] arrayListArray = new ArrayList[4];
482      arrayListArray[0] = new ArrayList();
483      arrayListArray[0].Add(arrayListArray);
484      arrayListArray[0].Add(arrayListArray);
485      arrayListArray[1] = new ArrayList();
486      arrayListArray[1].Add(arrayListArray);
487      arrayListArray[2] = new ArrayList();
488      arrayListArray[2].Add(arrayListArray);
489      arrayListArray[2].Add(arrayListArray);
490      Array a = Array.CreateInstance(
491                              typeof(object),
492                              new[] { 1, 2 }, new[] { 3, 4 });
493      arrayListArray[2].Add(a);
494      serializer.Serialize(arrayListArray, tempFile);
495      object o = serializer.Deserialize(tempFile);
496      Assert.AreEqual(
497        DebugStringGenerator.Serialize(arrayListArray),
498        DebugStringGenerator.Serialize(o));
499      ArrayList[] newArray = (ArrayList[])o;
500      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
501      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
502      Assert.AreSame(newArray, newArray[0][0]);
503      Assert.AreSame(newArray, newArray[2][1]);
504    }
505
506    [TestMethod]
507    [TestCategory("Persistence")]
508    [TestProperty("Time", "short")]
509    public void CustomSerializationProperty() {
510      ProtoBufSerializer serializer = new ProtoBufSerializer();
511      Manager m = new Manager();
512      serializer.Serialize(m, tempFile);
513      Manager newM = (Manager)serializer.Deserialize(tempFile);
514      Assert.AreNotEqual(
515        DebugStringGenerator.Serialize(m),
516        DebugStringGenerator.Serialize(newM));
517      Assert.AreEqual(m.dbl, newM.dbl);
518      Assert.AreEqual(m.lastLoadTime, new DateTime());
519      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
520      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
521    }
522
523    [TestMethod]
524    [TestCategory("Persistence")]
525    [TestProperty("Time", "short")]
526    public void Primitives() {
527      ProtoBufSerializer serializer = new ProtoBufSerializer();
528      PrimitivesTest sdt = new PrimitivesTest();
529      serializer.Serialize(sdt, tempFile);
530      object o = serializer.Deserialize(tempFile);
531      Assert.AreEqual(
532        DebugStringGenerator.Serialize(sdt),
533        DebugStringGenerator.Serialize(o));
534    }
535
536    [TestMethod]
537    [TestCategory("Persistence")]
538    [TestProperty("Time", "short")]
539    public void MultiDimensionalArray() {
540      ProtoBufSerializer serializer = new ProtoBufSerializer();
541      string[,] mDimString = new string[,] {
542        {"ora", "et", "labora"},
543        {"Beten", "und", "Arbeiten"}
544      };
545      serializer.Serialize(mDimString, tempFile);
546      object o = serializer.Deserialize(tempFile);
547      Assert.AreEqual(
548        DebugStringGenerator.Serialize(mDimString),
549        DebugStringGenerator.Serialize(o));
550    }
551
552    [StorableClass("87A331AF-14DC-48B3-B577-D49065743BE6")]
553    public class NestedType {
554      [Storable]
555      private string value = "value";
556      public override bool Equals(object obj) {
557        NestedType nt = obj as NestedType;
558        if (nt == null)
559          throw new NotSupportedException();
560        return nt.value == value;
561      }
562      public override int GetHashCode() {
563        return value.GetHashCode();
564      }
565    }
566
567    [TestMethod]
568    [TestCategory("Persistence")]
569    [TestProperty("Time", "short")]
570    public void NestedTypeTest() {
571      ProtoBufSerializer serializer = new ProtoBufSerializer();
572      NestedType t = new NestedType();
573      serializer.Serialize(t, tempFile);
574      object o = serializer.Deserialize(tempFile);
575      Assert.AreEqual(
576        DebugStringGenerator.Serialize(t),
577        DebugStringGenerator.Serialize(o));
578      Assert.IsTrue(t.Equals(o));
579    }
580
581
582    [TestMethod]
583    [TestCategory("Persistence")]
584    [TestProperty("Time", "short")]
585    public void SimpleArray() {
586      ProtoBufSerializer serializer = new ProtoBufSerializer();
587      string[] strings = { "ora", "et", "labora" };
588      serializer.Serialize(strings, tempFile);
589      object o = serializer.Deserialize(tempFile);
590      Assert.AreEqual(
591        DebugStringGenerator.Serialize(strings),
592        DebugStringGenerator.Serialize(o));
593    }
594
595    [TestMethod]
596    [TestCategory("Persistence")]
597    [TestProperty("Time", "short")]
598    public void PrimitiveRoot() {
599      ProtoBufSerializer serializer = new ProtoBufSerializer();
600      serializer.Serialize(12.3f, tempFile);
601      object o = serializer.Deserialize(tempFile);
602      Assert.AreEqual(
603        DebugStringGenerator.Serialize(12.3f),
604        DebugStringGenerator.Serialize(o));
605    }
606
607    private string formatFullMemberName(MemberInfo mi) {
608      return new StringBuilder()
609        .Append(mi.DeclaringType.Assembly.GetName().Name)
610        .Append(": ")
611        .Append(mi.DeclaringType.Namespace)
612        .Append('.')
613        .Append(mi.DeclaringType.Name)
614        .Append('.')
615        .Append(mi.Name).ToString();
616    }
617
618    public void CodingConventions() {
619      List<string> lowerCaseMethodNames = new List<string>();
620      List<string> lowerCaseProperties = new List<string>();
621      List<string> lowerCaseFields = new List<string>();
622      foreach (Assembly a in PluginLoader.Assemblies) {
623        if (!a.GetName().Name.StartsWith("HeuristicLab"))
624          continue;
625        foreach (Type t in a.GetTypes()) {
626          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
627            if (mi.DeclaringType.Name.StartsWith("<>"))
628              continue;
629            if (char.IsLower(mi.Name[0])) {
630              if (mi.MemberType == MemberTypes.Field)
631                lowerCaseFields.Add(formatFullMemberName(mi));
632              if (mi.MemberType == MemberTypes.Property)
633                lowerCaseProperties.Add(formatFullMemberName(mi));
634              if (mi.MemberType == MemberTypes.Method &&
635                !mi.Name.StartsWith("get_") &&
636                !mi.Name.StartsWith("set_") &&
637                !mi.Name.StartsWith("add_") &&
638                !mi.Name.StartsWith("remove_") &&
639                !mi.Name.StartsWith("op_"))
640                lowerCaseMethodNames.Add(formatFullMemberName(mi));
641            }
642          }
643        }
644      }
645      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
646      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
647      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
648    }
649
650    [TestMethod]
651    [TestCategory("Persistence")]
652    [TestProperty("Time", "short")]
653    public void Enums() {
654      ProtoBufSerializer serializer = new ProtoBufSerializer();
655      EnumTest et = new EnumTest();
656      et.simpleEnum = SimpleEnum.two;
657      et.complexEnum = ComplexEnum.three;
658      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
659      serializer.Serialize(et, tempFile);
660      EnumTest newEt = (EnumTest)serializer.Deserialize(tempFile);
661      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
662      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
663      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
664    }
665
666    [TestMethod]
667    [TestCategory("Persistence")]
668    [TestProperty("Time", "short")]
669    public void TestAliasingWithOverriddenEquals() {
670      ProtoBufSerializer serializer = new ProtoBufSerializer();
671      List<IntWrapper> ints = new List<IntWrapper>();
672      ints.Add(new IntWrapper(1));
673      ints.Add(new IntWrapper(1));
674      Assert.AreEqual(ints[0], ints[1]);
675      Assert.AreNotSame(ints[0], ints[1]);
676      serializer.Serialize(ints, tempFile);
677      List<IntWrapper> newInts = (List<IntWrapper>)serializer.Deserialize(tempFile);
678      Assert.AreEqual(newInts[0].Value, 1);
679      Assert.AreEqual(newInts[1].Value, 1);
680      Assert.AreEqual(newInts[0], newInts[1]);
681      Assert.AreNotSame(newInts[0], newInts[1]);
682    }
683
684    [TestMethod]
685    [TestCategory("Persistence")]
686    [TestProperty("Time", "short")]
687    public void NonDefaultConstructorTest() {
688      ProtoBufSerializer serializer = new ProtoBufSerializer();
689      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
690      try {
691        serializer.Serialize(c, tempFile);
692        Assert.Fail("Exception not thrown");
693      }
694      catch (PersistenceException) {
695      }
696    }
697
698    [TestMethod]
699    [TestCategory("Persistence")]
700    [TestProperty("Time", "short")]
701    public void TestSavingException() {
702      ProtoBufSerializer serializer = new ProtoBufSerializer();
703      List<int> list = new List<int> { 1, 2, 3 };
704      serializer.Serialize(list, tempFile);
705      NonSerializable s = new NonSerializable();
706      try {
707        serializer.Serialize(s, tempFile);
708        Assert.Fail("Exception expected");
709      }
710      catch (PersistenceException) { }
711      List<int> newList = (List<int>)serializer.Deserialize(tempFile);
712      Assert.AreEqual(list[0], newList[0]);
713      Assert.AreEqual(list[1], newList[1]);
714    }
715
716    [TestMethod]
717    [TestCategory("Persistence")]
718    [TestProperty("Time", "short")]
719    public void TestTypeStringConversion() {
720      string name = typeof(List<int>[]).AssemblyQualifiedName;
721      string shortName =
722        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
723      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
724      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
725      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
726    }
727
728    [TestMethod]
729    [TestCategory("Persistence")]
730    [TestProperty("Time", "short")]
731    public void TestHexadecimalPublicKeyToken() {
732      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
733      string shortName = "TestClass, TestAssembly";
734      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
735      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
736    }
737
738    [TestMethod]
739    [TestCategory("Persistence")]
740    [TestProperty("Time", "short")]
741    public void InheritanceTest() {
742      ProtoBufSerializer serializer = new ProtoBufSerializer();
743      New n = new New();
744      serializer.Serialize(n, tempFile);
745      New nn = (New)serializer.Deserialize(tempFile);
746      Assert.AreEqual(n.Name, nn.Name);
747      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
748    }
749
750    [StorableClass("B963EF51-12B4-432E-8C54-88F026F9ACE2")]
751    class Child {
752      [Storable]
753      public GrandParent grandParent;
754    }
755
756    [StorableClass("E66E9606-967A-4C35-A361-F6F0D21C064A")]
757    class Parent {
758      [Storable]
759      public Child child;
760    }
761
762    [StorableClass("34D3893A-57AD-4F72-878B-81D6FA3F14A9")]
763    class GrandParent {
764      [Storable]
765      public Parent parent;
766    }
767
768    [TestMethod]
769    [TestCategory("Persistence")]
770    [TestProperty("Time", "short")]
771    public void InstantiateParentChainReference() {
772      ProtoBufSerializer serializer = new ProtoBufSerializer();
773      GrandParent gp = new GrandParent();
774      gp.parent = new Parent();
775      gp.parent.child = new Child();
776      gp.parent.child.grandParent = gp;
777      Assert.AreSame(gp, gp.parent.child.grandParent);
778      serializer.Serialize(gp, tempFile);
779      GrandParent newGp = (GrandParent)serializer.Deserialize(tempFile);
780      Assert.AreSame(newGp, newGp.parent.child.grandParent);
781    }
782
783    struct TestStruct {
784      int value;
785      int PropertyValue { get; set; }
786      public TestStruct(int value)
787        : this() {
788        this.value = value;
789        PropertyValue = value;
790      }
791    }
792
793    [TestMethod]
794    [TestCategory("Persistence")]
795    [TestProperty("Time", "short")]
796    public void StructTest() {
797      ProtoBufSerializer serializer = new ProtoBufSerializer();
798      TestStruct s = new TestStruct(10);
799      serializer.Serialize(s, tempFile);
800      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
801      Assert.AreEqual(s, newS);
802    }
803
804    [TestMethod]
805    [TestCategory("Persistence")]
806    [TestProperty("Time", "short")]
807    public void PointTest() {
808      ProtoBufSerializer serializer = new ProtoBufSerializer();
809      Point p = new Point(12, 34);
810      serializer.Serialize(p, tempFile);
811      Point newP = (Point)serializer.Deserialize(tempFile);
812      Assert.AreEqual(p, newP);
813    }
814
815    [TestMethod]
816    [TestCategory("Persistence")]
817    [TestProperty("Time", "short")]
818    public void NullableValueTypes() {
819      ProtoBufSerializer serializer = new ProtoBufSerializer();
820      double?[] d = new double?[] { null, 1, 2, 3 };
821      serializer.Serialize(d, tempFile);
822      double?[] newD = (double?[])serializer.Deserialize(tempFile);
823      Assert.AreEqual(d[0], newD[0]);
824      Assert.AreEqual(d[1], newD[1]);
825      Assert.AreEqual(d[2], newD[2]);
826      Assert.AreEqual(d[3], newD[3]);
827    }
828
829    [TestMethod]
830    [TestCategory("Persistence")]
831    [TestProperty("Time", "short")]
832    public void BitmapTest() {
833      ProtoBufSerializer serializer = new ProtoBufSerializer();
834      Icon icon = System.Drawing.SystemIcons.Hand;
835      Bitmap bitmap = icon.ToBitmap();
836      serializer.Serialize(bitmap, tempFile);
837      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
838
839      Assert.AreEqual(bitmap.Size, newBitmap.Size);
840      for (int i = 0; i < bitmap.Size.Width; i++)
841        for (int j = 0; j < bitmap.Size.Height; j++)
842          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
843    }
844
845    [StorableClass("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
846    private class PersistenceHooks {
847      [Storable]
848      public int a;
849      [Storable]
850      public int b;
851      public int sum;
852      public bool WasSerialized { get; private set; }
853      [StorableHook(HookType.BeforeSerialization)]
854      void PreSerializationHook() {
855        WasSerialized = true;
856      }
857      [StorableHook(HookType.AfterDeserialization)]
858      void PostDeserializationHook() {
859        sum = a + b;
860      }
861    }
862
863    [TestMethod]
864    [TestCategory("Persistence")]
865    [TestProperty("Time", "short")]
866    public void HookTest() {
867      ProtoBufSerializer serializer = new ProtoBufSerializer();
868      PersistenceHooks hookTest = new PersistenceHooks();
869      hookTest.a = 2;
870      hookTest.b = 5;
871      Assert.IsFalse(hookTest.WasSerialized);
872      Assert.AreEqual(hookTest.sum, 0);
873      serializer.Serialize(hookTest, tempFile);
874      Assert.IsTrue(hookTest.WasSerialized);
875      Assert.AreEqual(hookTest.sum, 0);
876      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
877      Assert.AreEqual(newHookTest.a, hookTest.a);
878      Assert.AreEqual(newHookTest.b, hookTest.b);
879      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
880      Assert.IsFalse(newHookTest.WasSerialized);
881    }
882
883    [StorableClass("A35D71DF-397F-4910-A950-ED6923BE9483")]
884    private class CustomConstructor {
885      public string Value = "none";
886      public CustomConstructor() {
887        Value = "default";
888      }
889      [StorableConstructor]
890      private CustomConstructor(bool deserializing) {
891        Assert.IsTrue(deserializing);
892        Value = "persistence";
893      }
894    }
895
896    [TestMethod]
897    [TestCategory("Persistence")]
898    [TestProperty("Time", "short")]
899    public void TestCustomConstructor() {
900      ProtoBufSerializer serializer = new ProtoBufSerializer();
901      CustomConstructor cc = new CustomConstructor();
902      Assert.AreEqual(cc.Value, "default");
903      serializer.Serialize(cc, tempFile);
904      CustomConstructor newCC = (CustomConstructor)serializer.Deserialize(tempFile);
905      Assert.AreEqual(newCC.Value, "persistence");
906    }
907
908    [StorableClass("D276E825-1F35-4BAC-8937-9ABC91D5C316")]
909    public class ExplodingDefaultConstructor {
910      public ExplodingDefaultConstructor() {
911        throw new Exception("this constructor will always fail");
912      }
913      public ExplodingDefaultConstructor(string password) {
914      }
915    }
916
917    [TestMethod]
918    [TestCategory("Persistence")]
919    [TestProperty("Time", "short")]
920    public void TestConstructorExceptionUnwrapping() {
921      ProtoBufSerializer serializer = new ProtoBufSerializer();
922      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
923      serializer.Serialize(x, tempFile);
924      try {
925        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)serializer.Deserialize(tempFile);
926        Assert.Fail("Exception expected");
927      }
928      catch (PersistenceException pe) {
929        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
930      }
931    }
932
933    [TestMethod]
934    [TestCategory("Persistence")]
935    [TestProperty("Time", "short")]
936    public void TestRejectionJustifications() {
937      ProtoBufSerializer serializer = new ProtoBufSerializer();
938      NonSerializable ns = new NonSerializable();
939      try {
940        serializer.Serialize(ns, tempFile);
941        Assert.Fail("PersistenceException expected");
942      }
943      catch (PersistenceException x) {
944        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
945      }
946    }
947
948    [TestMethod]
949    [TestCategory("Persistence")]
950    [TestProperty("Time", "short")]
951    public void TestStreaming() {
952      ProtoBufSerializer serializer = new ProtoBufSerializer();
953      using (MemoryStream stream = new MemoryStream()) {
954        Root r = InitializeComplexStorable();
955        serializer.Serialize(r, stream);
956        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
957          Root newR = (Root)serializer.Deserialize(stream2);
958          CompareComplexStorables(r, newR);
959        }
960      }
961    }
962
963    [StorableClass("4921031B-CB61-4677-97AD-9236A4CEC200")]
964    public class HookInheritanceTestBase {
965      [Storable]
966      public object a;
967      public object link;
968      [StorableHook(HookType.AfterDeserialization)]
969      private void relink() {
970        link = a;
971      }
972    }
973
974    [StorableClass("321CEE0A-5201-4CE2-B135-2343890D96BF")]
975    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
976      [Storable]
977      public object b;
978      [StorableHook(HookType.AfterDeserialization)]
979      private void relink() {
980        Assert.AreSame(a, link);
981        link = b;
982      }
983    }
984
985    [TestMethod]
986    [TestCategory("Persistence")]
987    [TestProperty("Time", "short")]
988    public void TestLinkInheritance() {
989      ProtoBufSerializer serializer = new ProtoBufSerializer();
990      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
991      c.a = new object();
992      serializer.Serialize(c, tempFile);
993      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)serializer.Deserialize(tempFile);
994      Assert.AreSame(c.b, c.link);
995    }
996
997    [StorableClass(StorableClassType.AllFields, "B9AB42E8-1932-425B-B4CF-F31F07EAC599")]
998    public class AllFieldsStorable {
999      public int Value1 = 1;
1000      [Storable]
1001      public int Value2 = 2;
1002      public int Value3 { get; private set; }
1003      public int Value4 { get; private set; }
1004      [StorableConstructor]
1005      public AllFieldsStorable(bool isDeserializing) {
1006        if (!isDeserializing) {
1007          Value1 = 12;
1008          Value2 = 23;
1009          Value3 = 34;
1010          Value4 = 56;
1011        }
1012      }
1013    }
1014
1015    [TestMethod]
1016    [TestCategory("Persistence")]
1017    [TestProperty("Time", "short")]
1018    public void TestStorableClassDiscoveryAllFields() {
1019      ProtoBufSerializer serializer = new ProtoBufSerializer();
1020      AllFieldsStorable afs = new AllFieldsStorable(false);
1021      serializer.Serialize(afs, tempFile);
1022      AllFieldsStorable newAfs = (AllFieldsStorable)serializer.Deserialize(tempFile);
1023      Assert.AreEqual(afs.Value1, newAfs.Value1);
1024      Assert.AreEqual(afs.Value2, newAfs.Value2);
1025      Assert.AreEqual(0, newAfs.Value3);
1026      Assert.AreEqual(0, newAfs.Value4);
1027    }
1028
1029    [StorableClass(StorableClassType.AllProperties, "CB7DC31C-AEF3-4EB8-91CA-248B767E9F92")]
1030    public class AllPropertiesStorable {
1031      public int Value1 = 1;
1032      [Storable]
1033      public int Value2 = 2;
1034      public int Value3 { get; private set; }
1035      public int Value4 { get; private set; }
1036      [StorableConstructor]
1037      public AllPropertiesStorable(bool isDeserializing) {
1038        if (!isDeserializing) {
1039          Value1 = 12;
1040          Value2 = 23;
1041          Value3 = 34;
1042          Value4 = 56;
1043        }
1044      }
1045    }
1046
1047    [TestMethod]
1048    [TestCategory("Persistence")]
1049    [TestProperty("Time", "short")]
1050    public void TestStorableClassDiscoveryAllProperties() {
1051      ProtoBufSerializer serializer = new ProtoBufSerializer();
1052      AllPropertiesStorable afs = new AllPropertiesStorable(false);
1053      serializer.Serialize(afs, tempFile);
1054      AllPropertiesStorable newAfs = (AllPropertiesStorable)serializer.Deserialize(tempFile);
1055      Assert.AreEqual(1, newAfs.Value1);
1056      Assert.AreEqual(2, newAfs.Value2);
1057      Assert.AreEqual(afs.Value3, newAfs.Value3);
1058      Assert.AreEqual(afs.Value4, newAfs.Value4);
1059
1060    }
1061
1062    [StorableClass(StorableClassType.AllFieldsAndAllProperties, "0AD8D68F-E0FF-4FA8-8A72-1148CD91A2B9")]
1063    public class AllFieldsAndAllPropertiesStorable {
1064      public int Value1 = 1;
1065      [Storable]
1066      public int Value2 = 2;
1067      public int Value3 { get; private set; }
1068      public int Value4 { get; private set; }
1069      [StorableConstructor]
1070      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1071        if (!isDeserializing) {
1072          Value1 = 12;
1073          Value2 = 23;
1074          Value3 = 34;
1075          Value4 = 56;
1076        }
1077      }
1078    }
1079
1080    [TestMethod]
1081    [TestCategory("Persistence")]
1082    [TestProperty("Time", "short")]
1083    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1084      ProtoBufSerializer serializer = new ProtoBufSerializer();
1085      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1086      serializer.Serialize(afs, tempFile);
1087      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)serializer.Deserialize(tempFile);
1088      Assert.AreEqual(afs.Value1, newAfs.Value1);
1089      Assert.AreEqual(afs.Value2, newAfs.Value2);
1090      Assert.AreEqual(afs.Value3, newAfs.Value3);
1091      Assert.AreEqual(afs.Value4, newAfs.Value4);
1092    }
1093
1094    [StorableClass(StorableClassType.MarkedOnly, "0D94E6D4-64E3-4637-B1EE-DEF2B3F6E2E0")]
1095    public class MarkedOnlyStorable {
1096      public int Value1 = 1;
1097      [Storable]
1098      public int Value2 = 2;
1099      public int Value3 { get; private set; }
1100      public int Value4 { get; private set; }
1101      [StorableConstructor]
1102      public MarkedOnlyStorable(bool isDeserializing) {
1103        if (!isDeserializing) {
1104          Value1 = 12;
1105          Value2 = 23;
1106          Value3 = 34;
1107          Value4 = 56;
1108        }
1109      }
1110    }
1111
1112    [TestMethod]
1113    [TestCategory("Persistence")]
1114    [TestProperty("Time", "short")]
1115    public void TestStorableClassDiscoveryMarkedOnly() {
1116      ProtoBufSerializer serializer = new ProtoBufSerializer();
1117      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1118      serializer.Serialize(afs, tempFile);
1119      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)serializer.Deserialize(tempFile);
1120      Assert.AreEqual(1, newAfs.Value1);
1121      Assert.AreEqual(afs.Value2, newAfs.Value2);
1122      Assert.AreEqual(0, newAfs.Value3);
1123      Assert.AreEqual(0, newAfs.Value4);
1124    }
1125
1126    [TestMethod]
1127    [TestCategory("Persistence")]
1128    [TestProperty("Time", "short")]
1129    public void TestLineEndings() {
1130      ProtoBufSerializer serializer = new ProtoBufSerializer();
1131      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1132      List<string> lines = new List<string>();
1133      foreach (var br in lineBreaks)
1134        lines.Add("line1" + br + "line2");
1135      serializer.Serialize(lines, tempFile);
1136      List<string> newLines = (List<string>)serializer.Deserialize(tempFile);
1137      Assert.AreEqual(lines.Count, newLines.Count);
1138      for (int i = 0; i < lineBreaks.Count; i++) {
1139        Assert.AreEqual(lines[i], newLines[i]);
1140      }
1141    }
1142
1143    [TestMethod]
1144    [TestCategory("Persistence")]
1145    [TestProperty("Time", "short")]
1146    public void TestSpecialNumbers() {
1147      ProtoBufSerializer serializer = new ProtoBufSerializer();
1148      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1149      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1150      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1151      Assert.IsTrue(double.IsNaN(specials[2]));
1152      serializer.Serialize(specials, tempFile);
1153      List<double> newSpecials = (List<double>)serializer.Deserialize(tempFile);
1154      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1155      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1156      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1157    }
1158
1159    [TestMethod]
1160    [TestCategory("Persistence")]
1161    [TestProperty("Time", "short")]
1162    public void TestStringSplit() {
1163      string s = "1.2;2.3;3.4;;;4.9";
1164      var l = s.EnumerateSplit(';').ToList();
1165      Assert.AreEqual("1.2", l[0]);
1166      Assert.AreEqual("2.3", l[1]);
1167      Assert.AreEqual("3.4", l[2]);
1168      Assert.AreEqual("4.9", l[3]);
1169    }
1170
1171    private class IdentityComparer<T> : IEqualityComparer<T> {
1172
1173      public bool Equals(T x, T y) {
1174        return x.Equals(y);
1175      }
1176
1177      public int GetHashCode(T obj) {
1178        return obj.GetHashCode();
1179      }
1180    }
1181
1182    [TestMethod]
1183    [TestCategory("Persistence")]
1184    [TestProperty("Time", "short")]
1185    public void TestHashSetSerializer() {
1186      ProtoBufSerializer serializer = new ProtoBufSerializer();
1187      var hashSets = new List<HashSet<int>>() {
1188        new HashSet<int>(new[] { 1, 2, 3 }),
1189        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1190      };
1191      serializer.Serialize(hashSets, tempFile);
1192      var newHashSets = (List<HashSet<int>>)serializer.Deserialize(tempFile);
1193      Assert.IsTrue(newHashSets[0].Contains(1));
1194      Assert.IsTrue(newHashSets[0].Contains(2));
1195      Assert.IsTrue(newHashSets[0].Contains(3));
1196      Assert.IsTrue(newHashSets[1].Contains(4));
1197      Assert.IsTrue(newHashSets[1].Contains(5));
1198      Assert.IsTrue(newHashSets[1].Contains(6));
1199      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1200      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1201    }
1202
1203    [TestMethod]
1204    [TestCategory("Persistence")]
1205    [TestProperty("Time", "short")]
1206    public void TestConcreteDictionarySerializer() {
1207      ProtoBufSerializer serializer = new ProtoBufSerializer();
1208      var dictionaries = new List<Dictionary<int, int>>() {
1209        new Dictionary<int, int>(),
1210        new Dictionary<int, int>(new IdentityComparer<int>()),
1211      };
1212      dictionaries[0].Add(1, 1);
1213      dictionaries[0].Add(2, 2);
1214      dictionaries[0].Add(3, 3);
1215      dictionaries[1].Add(4, 4);
1216      dictionaries[1].Add(5, 5);
1217      dictionaries[1].Add(6, 6);
1218      serializer.Serialize(dictionaries, tempFile);
1219      var newDictionaries = (List<Dictionary<int, int>>)serializer.Deserialize(tempFile);
1220      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1221      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1222      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1223      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1224      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1225      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1226      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1227      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1228      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1229      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1230      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1231      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1232      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1233      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1234    }
1235
1236    [StorableClass("A9B0D7FB-0CAF-4DD7-9045-EA136F9176F7")]
1237    public class ReadOnlyFail {
1238      [Storable]
1239      public string ReadOnly {
1240        get { return "fail"; }
1241      }
1242    }
1243
1244    [TestMethod]
1245    [TestCategory("Persistence")]
1246    [TestProperty("Time", "short")]
1247    public void TestReadOnlyFail() {
1248      ProtoBufSerializer serializer = new ProtoBufSerializer();
1249      try {
1250        serializer.Serialize(new ReadOnlyFail(), tempFile);
1251        Assert.Fail("Exception expected");
1252      }
1253      catch (PersistenceException) {
1254      }
1255      catch {
1256        Assert.Fail("PersistenceException expected");
1257      }
1258    }
1259
1260
1261    [StorableClass("2C9CC576-6823-4784-817B-37C8AF0B1C29")]
1262    public class WriteOnlyFail {
1263      [Storable]
1264      public string WriteOnly {
1265        set { throw new InvalidOperationException("this property should never be set."); }
1266      }
1267    }
1268
1269    [TestMethod]
1270    [TestCategory("Persistence")]
1271    [TestProperty("Time", "short")]
1272    public void TestWriteOnlyFail() {
1273      ProtoBufSerializer serializer = new ProtoBufSerializer();
1274      try {
1275        serializer.Serialize(new WriteOnlyFail(), tempFile);
1276        Assert.Fail("Exception expected");
1277      }
1278      catch (PersistenceException) {
1279      }
1280      catch {
1281        Assert.Fail("PersistenceException expected.");
1282      }
1283    }
1284
1285    [StorableClass("8052D9E3-6DDD-4AE1-9B5B-67C6D5436512")]
1286    public class OneWayTest {
1287      public OneWayTest() { this.value = "default"; }
1288      public string value;
1289      [Storable(AllowOneWay = true)]
1290      public string ReadOnly {
1291        get { return "ReadOnly"; }
1292      }
1293      [Storable(AllowOneWay = true)]
1294      public string WriteOnly {
1295        set { this.value = value; }
1296      }
1297    }
1298
1299    //TODO
1300    /* [TestMethod]
1301     [TestCategory("Persistence")]
1302     [TestProperty("Time", "short")]
1303     public void TestTypeCacheExport() {
1304       ProtoBufSerializer serializer = new ProtoBufSerializer();
1305       var test = new List<List<int>>();
1306       test.Add(new List<int>() { 1, 2, 3 });
1307       IEnumerable<Type> types;
1308       using (var stream = new MemoryStream()) {
1309         XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1310       }
1311       List<Type> t = new List<Type>(types);
1312       // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1313       Assert.IsTrue(t.Contains(typeof(List<int>)));
1314       Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1315       Assert.AreEqual(t.Count, 2);
1316     }*/
1317
1318    [TestMethod]
1319    [TestCategory("Persistence")]
1320    [TestProperty("Time", "short")]
1321    public void TupleTest() {
1322      var t1 = Tuple.Create(1);
1323      var t2 = Tuple.Create('1', "2");
1324      var t3 = Tuple.Create(3.0, 3f, 5);
1325      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1326      var tuple = Tuple.Create(t1, t2, t3, t4);
1327      XmlGenerator.Serialize(tuple, tempFile);
1328      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);
1329      Assert.AreEqual(tuple, newTuple);
1330    }
1331
1332    [TestMethod]
1333    [TestCategory("Persistence")]
1334    [TestProperty("Time", "short")]
1335    public void FontTest() {
1336      ProtoBufSerializer serializer = new ProtoBufSerializer();
1337      List<Font> fonts = new List<Font>() {
1338        new Font(FontFamily.GenericSansSerif, 12),
1339        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1340        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1341        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1342      };
1343      serializer.Serialize(fonts, tempFile);
1344      var newFonts = (List<Font>)serializer.Deserialize(tempFile);
1345      Assert.AreEqual(fonts[0], newFonts[0]);
1346      Assert.AreEqual(fonts[1], newFonts[1]);
1347      Assert.AreEqual(fonts[2], newFonts[2]);
1348      Assert.AreEqual(fonts[3], newFonts[3]);
1349    }
1350
1351    [TestMethod]
1352    [TestCategory("Persistence")]
1353    [TestProperty("Time", "medium")]
1354    public void ConcurrencyTest() {
1355      ProtoBufSerializer serializer = new ProtoBufSerializer();
1356      int n = 20;
1357      Task[] tasks = new Task[n];
1358      for (int i = 0; i < n; i++) {
1359        tasks[i] = Task.Factory.StartNew((idx) => {
1360          byte[] data;
1361          using (var stream = new MemoryStream()) {
1362            serializer.Serialize(new GeneticAlgorithm(), stream);
1363            data = stream.ToArray();
1364          }
1365        }, i);
1366      }
1367      Task.WaitAll(tasks);
1368    }
1369
1370    [TestMethod]
1371    [TestCategory("Persistence")]
1372    [TestProperty("Time", "medium")]
1373    public void ConcurrentBitmapTest() {
1374      ProtoBufSerializer serializer = new ProtoBufSerializer();
1375      Bitmap b = new Bitmap(300, 300);
1376      System.Random r = new System.Random();
1377      for (int x = 0; x < b.Height; x++) {
1378        for (int y = 0; y < b.Width; y++) {
1379          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1380        }
1381      }
1382      Task[] tasks = new Task[20];
1383      byte[][] datas = new byte[tasks.Length][];
1384      for (int i = 0; i < tasks.Length; i++) {
1385        tasks[i] = Task.Factory.StartNew((idx) => {
1386          using (var stream = new MemoryStream()) {
1387            serializer.Serialize(b, stream);
1388            datas[(int)idx] = stream.ToArray();
1389          }
1390        }, i);
1391      }
1392      Task.WaitAll(tasks);
1393    }
1394
1395    public class G<T, T2> {
1396      public class S { }
1397      public class S2<T3, T4> { }
1398    }
1399
1400
1401    [TestMethod]
1402    [TestCategory("Persistence")]
1403    [TestProperty("Time", "short")]
1404    public void TestSpecialCharacters() {
1405      ProtoBufSerializer serializer = new ProtoBufSerializer();
1406      var s = "abc" + "\x15" + "def";
1407      serializer.Serialize(s, tempFile);
1408      var newS = serializer.Deserialize(tempFile);
1409      Assert.AreEqual(s, newS);
1410    }
1411
1412    [TestMethod]
1413    [TestCategory("Persistence")]
1414    [TestProperty("Time", "short")]
1415    public void TestByteArray() {
1416      ProtoBufSerializer serializer = new ProtoBufSerializer();
1417      var b = new byte[3];
1418      b[0] = 0;
1419      b[1] = 200;
1420      b[2] = byte.MaxValue;
1421      serializer.Serialize(b, tempFile);
1422      var newB = (byte[])serializer.Deserialize(tempFile);
1423      CollectionAssert.AreEqual(b, newB);
1424    }
1425
1426    [TestMethod]
1427    [TestCategory("Persistence")]
1428    [TestProperty("Time", "short")]
1429    public void TestOptionalNumberEnumerable() {
1430      ProtoBufSerializer serializer = new ProtoBufSerializer();
1431      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
1432      serializer.Serialize(values, tempFile);
1433      var newValues = (List<double?>)serializer.Deserialize(tempFile);
1434      CollectionAssert.AreEqual(values, newValues);
1435    }
1436
1437    [TestMethod]
1438    [TestCategory("Persistence")]
1439    [TestProperty("Time", "short")]
1440    public void TestOptionalDateTimeEnumerable() {
1441      ProtoBufSerializer serializer = new ProtoBufSerializer();
1442      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
1443        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
1444      serializer.Serialize(values, tempFile);
1445      var newValues = (List<DateTime?>)serializer.Deserialize(tempFile);
1446      CollectionAssert.AreEqual(values, newValues);
1447    }
1448
1449    [TestMethod]
1450    [TestCategory("Persistence")]
1451    [TestProperty("Time", "short")]
1452    public void TestStringEnumerable() {
1453      ProtoBufSerializer serializer = new ProtoBufSerializer();
1454      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
1455      serializer.Serialize(values, tempFile);
1456      var newValues = (List<String>)serializer.Deserialize(tempFile);
1457      CollectionAssert.AreEqual(values, newValues);
1458    }
1459
1460    [TestMethod]
1461    [TestCategory("Persistence")]
1462    [TestProperty("Time", "short")]
1463    public void TestUnicodeCharArray() {
1464      ProtoBufSerializer serializer = new ProtoBufSerializer();
1465      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1466      serializer.Serialize(s, tempFile);
1467      var newS = (char[])serializer.Deserialize(tempFile);
1468      CollectionAssert.AreEqual(s, newS);
1469    }
1470
1471    [TestMethod]
1472    [TestCategory("Persistence")]
1473    [TestProperty("Time", "short")]
1474    public void TestUnicode() {
1475      ProtoBufSerializer serializer = new ProtoBufSerializer();
1476      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
1477      serializer.Serialize(s, tempFile);
1478      var newS = serializer.Deserialize(tempFile);
1479      Assert.AreEqual(s, newS);
1480    }
1481
1482    [TestMethod]
1483    [TestCategory("Persistence")]
1484    [TestProperty("Time", "short")]
1485    public void TestQueue() {
1486      ProtoBufSerializer serializer = new ProtoBufSerializer();
1487      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
1488      serializer.Serialize(q, tempFile);
1489      var newQ = (Queue<int>)serializer.Deserialize(tempFile);
1490      CollectionAssert.AreEqual(q, newQ);
1491    }
1492    #endregion
1493  }
1494}
Note: See TracBrowser for help on using the repository browser.