Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 6891

Last change on this file since 6891 was 6891, checked in by abeham, 13 years ago

#1619, #1628

  • reintegrated changes from branch
File size: 6.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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    public DeepCloneableCloningTest() {
40      excludedTypes = new HashSet<Type>();
41      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.Dataset));
42      excludedTypes.Add(typeof(HeuristicLab.Problems.TravelingSalesman.DistanceMatrix));
43      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.ClassificationEnsembleSolution));
44      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.RegressionEnsembleSolution));
45    }
46
47    private TestContext testContextInstance;
48    private readonly HashSet<Type> excludedTypes;
49
50    /// <summary>
51    ///Gets or sets the test context which provides
52    ///information about and functionality for the current test run.
53    ///</summary>
54    public TestContext TestContext {
55      get {
56        return testContextInstance;
57      }
58      set {
59        testContextInstance = value;
60      }
61    }
62
63    #region Additional test attributes
64    //
65    // You can use the following additional attributes as you write your tests:
66    //
67    // Use ClassInitialize to run code before running the first test in the class
68    // [ClassInitialize()]
69    // public static void MyClassInitialize(TestContext testContext) { }
70    //
71    // Use ClassCleanup to run code after all tests in a class have run
72    // [ClassCleanup()]
73    // public static void MyClassCleanup() { }
74    //
75    // Use TestInitialize to run code before running each test
76    // [TestInitialize()]
77    // public void MyTestInitialize() { }
78    //
79    // Use TestCleanup to run code after each test has run
80    // [TestCleanup()]
81    // public void MyTestCleanup() { }
82    //
83    #endregion
84
85    [TestMethod]
86    [DeploymentItem("SamplesExperimentFinished.hl")]
87    public void TestCloningFinishedExperiment() {
88      Experiment experiment = (Experiment)XmlParser.Deserialize("SamplesExperimentFinished.hl");
89
90      Experiment clone = (Experiment)experiment.Clone(new Cloner());
91      var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
92
93      Assert.IsTrue(ProcessEqualObjects(experiment, intersections));
94    }
95
96    [TestMethod]
97    public void TestCloningAllDeepCloneables() {
98      PluginLoader.Assemblies.ToArray();
99      bool success = true;
100      foreach (Type deepCloneableType in ApplicationManager.Manager.GetTypes(typeof(IDeepCloneable))) {
101        // skip types that explicitely choose not to deep-clone every member
102        if (excludedTypes.Contains(deepCloneableType)) continue;
103        // test only types contained in HL plugin assemblies
104        if (!PluginLoader.Assemblies.Contains(deepCloneableType.Assembly)) continue;
105        // test only instantiable types
106        if (deepCloneableType.IsAbstract || !deepCloneableType.IsClass) continue;
107
108        IDeepCloneable item = null;
109        try {
110          item = (IDeepCloneable)Activator.CreateInstance(deepCloneableType, nonPublic: false);
111        } catch { continue; } // no default constructor
112
113        var clone = (IDeepCloneable)item.Clone(new Cloner());
114        var intersections = CheckTotalInequality(item, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
115        if (!intersections.Any()) continue;
116
117        if (!ProcessEqualObjects(item, intersections))
118          success = false;
119      }
120      Assert.IsTrue(success, "There are potential errors in deep cloning objects.");
121    }
122
123    private IEnumerable<object> CheckTotalInequality(object original, object clone) {
124      var originalObjects = new HashSet<object>(original.GetObjectGraphObjects(true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
125      var clonedObjects = new HashSet<object>(clone.GetObjectGraphObjects(true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
126
127      return originalObjects.Intersect(clonedObjects);
128    }
129
130    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
131      bool success = true;
132      TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
133      foreach (object o in intersections) {
134        string typeName = o.GetType().FullName;
135        if (excludedTypes.Contains(o.GetType())) {
136          TestContext.WriteLine("Skipping excluded type " + typeName);
137        } else if (o is IDeepCloneable) {
138          string info = (o is IItem) ? ((IItem)o).ItemName + ((o is INamedItem) ? ", " + ((INamedItem)o).Name : String.Empty) : String.Empty;
139          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
140          success = false;
141        } else
142          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
143      }
144      return success;
145    }
146  }
147}
Note: See TracBrowser for help on using the repository browser.