Free cookie consent management tool by TermsFeed Policy Generator

source: branches/crossvalidation-2434/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 13578

Last change on this file since 13578 was 12722, checked in by abeham, 9 years ago

#2208: integrated orienteering problem into trunk

File size: 6.8 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.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Persistence.Default.Xml;
30using HeuristicLab.PluginInfrastructure;
31using Microsoft.VisualStudio.TestTools.UnitTesting;
32
33namespace HeuristicLab.Tests {
34  [TestClass]
35  public class DeepCloneableCloningTest {
36    private TestContext testContextInstance;
37    public TestContext TestContext {
38      get { return testContextInstance; }
39      set { testContextInstance = value; }
40    }
41
42    public DeepCloneableCloningTest() {
43      excludedTypes = new HashSet<Type> {
44        typeof (HeuristicLab.Problems.DataAnalysis.Dataset),
45        typeof (HeuristicLab.Problems.TravelingSalesman.DistanceMatrix),
46        typeof (HeuristicLab.Problems.DataAnalysis.ClassificationEnsembleSolution),
47        typeof (HeuristicLab.Problems.DataAnalysis.RegressionEnsembleSolution),
48        typeof (HeuristicLab.Problems.Orienteering.DistanceMatrix)
49      };
50      excludedTypes.Add(typeof(SymbolicExpressionGrammar).Assembly.GetType("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.EmptySymbolicExpressionTreeGrammar"));
51
52      foreach (var symbolType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbol)))
53        excludedTypes.Add(symbolType);
54      foreach (var grammarType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SymbolicExpressionGrammarBase)))
55        excludedTypes.Add(grammarType);
56    }
57
58    private readonly HashSet<Type> excludedTypes;
59
60    [TestMethod]
61    [TestCategory("General")]
62    [TestCategory("Essential")]
63    [TestProperty("Time", "long")]
64    public void TestCloningFinishedExperiment() {
65      Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl");
66
67      Experiment clone = (Experiment)experiment.Clone(new Cloner());
68      var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
69
70      Assert.IsTrue(ProcessEqualObjects(experiment, intersections));
71    }
72
73    [TestMethod]
74    [TestCategory("General")]
75    [TestCategory("Essential")]
76    [TestProperty("Time", "long")]
77    public void TestCloningAllDeepCloneables() {
78      PluginLoader.Assemblies.ToArray();
79      bool success = true;
80      foreach (Type deepCloneableType in ApplicationManager.Manager.GetTypes(typeof(IDeepCloneable))) {
81        // skip types that explicitely choose not to deep-clone every member
82        if (excludedTypes.Contains(deepCloneableType)) continue;
83        // test only types contained in HL plugin assemblies
84        if (!PluginLoader.Assemblies.Contains(deepCloneableType.Assembly)) continue;
85        // test only instantiable types
86        if (deepCloneableType.IsAbstract || !deepCloneableType.IsClass) continue;
87
88        IDeepCloneable item = null;
89        try {
90          item = (IDeepCloneable)Activator.CreateInstance(deepCloneableType, nonPublic: false);
91        } catch { continue; } // no default constructor
92
93        IDeepCloneable clone = null;
94        try {
95          clone = (IDeepCloneable)item.Clone(new Cloner());
96        } catch (Exception e) {
97          TestContext.WriteLine(Environment.NewLine + deepCloneableType.FullName + ":");
98          TestContext.WriteLine("ERROR! " + e.GetType().Name + @" was thrown during cloning.
99All IDeepCloneable items with a default constructor should be cloneable when using that constructor!");
100          success = false;
101          continue;
102        }
103        var intersections = CheckTotalInequality(item, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
104        if (!intersections.Any()) continue;
105
106        if (!ProcessEqualObjects(item, intersections))
107          success = false;
108      }
109      Assert.IsTrue(success, "There are potential errors in deep cloning objects.");
110    }
111
112    private IEnumerable<object> CheckTotalInequality(object original, object clone) {
113      var originalObjects = new HashSet<object>(original.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
114      var clonedObjects = new HashSet<object>(clone.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
115
116      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
117    }
118
119    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
120      bool success = true;
121      bool headerWritten = false;
122
123      foreach (object o in intersections) {
124        string typeName = o.GetType().FullName;
125        if (excludedTypes.Contains(o.GetType())) {
126          //TestContext.WriteLine("Skipping excluded type " + typeName);
127        } else if (o is IDeepCloneable) {
128          string info = (o is IItem) ? ((IItem)o).ItemName + ((o is INamedItem) ? ", " + ((INamedItem)o).Name : String.Empty) : String.Empty;
129          if (!headerWritten) {
130            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
131            headerWritten = true;
132          }
133          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
134          success = false;
135        } else {
136          Array array = o as Array;
137          if (array != null && array.Length == 0) continue; //arrays of length 0 are used inside empty collections
138          if (!headerWritten) {
139            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
140            headerWritten = true;
141          }
142          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
143        }
144      }
145      return success;
146    }
147  }
148}
Note: See TracBrowser for help on using the repository browser.