Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13847 was 13484, checked in by abeham, 9 years ago

#2221: integrated PTSP into trunk

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