Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab/3.3/Tests/DeepCloneableCloningTest.cs @ 6876

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

#1628

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