Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 10216

Last change on this file since 10216 was 8078, checked in by mkommend, 13 years ago

#1877: Corrected TestAllDeepCloneables unit test to use the ReferenceEqualityComparer.

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Optimization;
28using HeuristicLab.Persistence.Default.Xml;
29using HeuristicLab.PluginInfrastructure;
30using Microsoft.VisualStudio.TestTools.UnitTesting;
31
32namespace HeuristicLab_33.Tests {
33  /// <summary>
34  /// Summary description for DeepCloneableCloningTest
35  /// </summary>
36  [TestClass]
37  public class DeepCloneableCloningTest {
38
39    [ClassInitialize]
40    public static void MyClassInitialize(TestContext testContext) {
41      PluginLoader.Assemblies.Any();
42    }
43
44    public DeepCloneableCloningTest() {
45      excludedTypes = new HashSet<Type>();
46      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.Dataset));
47      excludedTypes.Add(typeof(HeuristicLab.Problems.TravelingSalesman.DistanceMatrix));
48      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.ClassificationEnsembleSolution));
49      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.RegressionEnsembleSolution));
50
51      foreach (var symbolType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbol)))
52        excludedTypes.Add(symbolType);
53      foreach (var grammarType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SymbolicExpressionGrammarBase)))
54        excludedTypes.Add(grammarType);
55    }
56
57    private TestContext testContextInstance;
58    private readonly HashSet<Type> excludedTypes;
59
60    /// <summary>
61    ///Gets or sets the test context which provides
62    ///information about and functionality for the current test run.
63    ///</summary>
64    public TestContext TestContext {
65      get {
66        return testContextInstance;
67      }
68      set {
69        testContextInstance = value;
70      }
71    }
72
73    #region Additional test attributes
74    //
75    // You can use the following additional attributes as you write your tests:
76    //
77    // Use ClassInitialize to run code before running the first test in the class
78    // [ClassInitialize()]
79    // public static void MyClassInitialize(TestContext testContext) { }
80    //
81    // Use ClassCleanup to run code after all tests in a class have run
82    // [ClassCleanup()]
83    // public static void MyClassCleanup() { }
84    //
85    // Use TestInitialize to run code before running each test
86    // [TestInitialize()]
87    // public void MyTestInitialize() { }
88    //
89    // Use TestCleanup to run code after each test has run
90    // [TestCleanup()]
91    // public void MyTestCleanup() { }
92    //
93    #endregion
94
95    [TestMethod]
96    [DeploymentItem(@"HeuristicLab-3.3\Resources\SamplesExperimentFinished.hl")]
97    public void TestCloningFinishedExperiment() {
98      Experiment experiment = (Experiment)XmlParser.Deserialize("SamplesExperimentFinished.hl");
99
100      Experiment clone = (Experiment)experiment.Clone(new Cloner());
101      var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
102
103      Assert.IsTrue(ProcessEqualObjects(experiment, intersections));
104    }
105
106    [TestMethod]
107    public void TestCloningAllDeepCloneables() {
108      PluginLoader.Assemblies.ToArray();
109      bool success = true;
110      foreach (Type deepCloneableType in ApplicationManager.Manager.GetTypes(typeof(IDeepCloneable))) {
111        // skip types that explicitely choose not to deep-clone every member
112        if (excludedTypes.Contains(deepCloneableType)) continue;
113        // test only types contained in HL plugin assemblies
114        if (!PluginLoader.Assemblies.Contains(deepCloneableType.Assembly)) continue;
115        // test only instantiable types
116        if (deepCloneableType.IsAbstract || !deepCloneableType.IsClass) continue;
117
118        IDeepCloneable item = null;
119        try {
120          item = (IDeepCloneable)Activator.CreateInstance(deepCloneableType, nonPublic: false);
121        }
122        catch { continue; } // no default constructor
123
124        IDeepCloneable clone = null;
125        try {
126          clone = (IDeepCloneable)item.Clone(new Cloner());
127        }
128        catch (Exception e) {
129          TestContext.WriteLine(Environment.NewLine + deepCloneableType.FullName + ":");
130          TestContext.WriteLine("ERROR! " + e.GetType().Name + @" was thrown during cloning.
131All IDeepCloneable items with a default constructor should be cloneable when using that constructor!");
132          success = false;
133          continue;
134        }
135        var intersections = CheckTotalInequality(item, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
136        if (!intersections.Any()) continue;
137
138        if (!ProcessEqualObjects(item, intersections))
139          success = false;
140      }
141      Assert.IsTrue(success, "There are potential errors in deep cloning objects.");
142    }
143
144    private IEnumerable<object> CheckTotalInequality(object original, object clone) {
145      var originalObjects = new HashSet<object>(original.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
146      var clonedObjects = new HashSet<object>(clone.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
147
148      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
149    }
150
151    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
152      bool success = true;
153      TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
154      foreach (object o in intersections) {
155        string typeName = o.GetType().FullName;
156        if (excludedTypes.Contains(o.GetType())) {
157          //TestContext.WriteLine("Skipping excluded type " + typeName);
158        } else if (o is IDeepCloneable) {
159          string info = (o is IItem) ? ((IItem)o).ItemName + ((o is INamedItem) ? ", " + ((INamedItem)o).Name : String.Empty) : String.Empty;
160          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
161          success = false;
162        } else
163          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
164      }
165      return success;
166    }
167  }
168}
Note: See TracBrowser for help on using the repository browser.