Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12440 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back 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() {
43      excludedTypes = new HashSet<Type>();
44      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.Dataset));
45      excludedTypes.Add(typeof(HeuristicLab.Problems.TravelingSalesman.DistanceMatrix));
46      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.ClassificationEnsembleSolution));
47      excludedTypes.Add(typeof(HeuristicLab.Problems.DataAnalysis.RegressionEnsembleSolution));
[11498]48      excludedTypes.Add(typeof(SymbolicExpressionGrammar).Assembly.GetType("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.EmptySymbolicExpressionTreeGrammar"));
[6921]49
50      foreach (var symbolType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbol)))
51        excludedTypes.Add(symbolType);
52      foreach (var grammarType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SymbolicExpressionGrammarBase)))
53        excludedTypes.Add(grammarType);
[6889]54    }
55
56    private readonly HashSet<Type> excludedTypes;
57
58    [TestMethod]
[9783]59    [TestCategory("General")]
60    [TestCategory("Essential")]
61    [TestProperty("Time", "long")]
[6889]62    public void TestCloningFinishedExperiment() {
[9955]63      Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl");
[6889]64
65      Experiment clone = (Experiment)experiment.Clone(new Cloner());
66      var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
67
68      Assert.IsTrue(ProcessEqualObjects(experiment, intersections));
69    }
70
71    [TestMethod]
[9783]72    [TestCategory("General")]
73    [TestCategory("Essential")]
74    [TestProperty("Time", "long")]
[6889]75    public void TestCloningAllDeepCloneables() {
76      PluginLoader.Assemblies.ToArray();
77      bool success = true;
78      foreach (Type deepCloneableType in ApplicationManager.Manager.GetTypes(typeof(IDeepCloneable))) {
79        // skip types that explicitely choose not to deep-clone every member
80        if (excludedTypes.Contains(deepCloneableType)) continue;
81        // test only types contained in HL plugin assemblies
82        if (!PluginLoader.Assemblies.Contains(deepCloneableType.Assembly)) continue;
83        // test only instantiable types
84        if (deepCloneableType.IsAbstract || !deepCloneableType.IsClass) continue;
85
86        IDeepCloneable item = null;
87        try {
88          item = (IDeepCloneable)Activator.CreateInstance(deepCloneableType, nonPublic: false);
[9783]89        }
90        catch { continue; } // no default constructor
[6889]91
[8046]92        IDeepCloneable clone = null;
93        try {
94          clone = (IDeepCloneable)item.Clone(new Cloner());
[9783]95        }
96        catch (Exception e) {
[8052]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!");
[8046]100          success = false;
101          continue;
102        }
[6889]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) {
[7467]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());
[6889]115
[8078]116      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
[6889]117    }
118
119    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
120      bool success = true;
[11782]121      bool headerWritten = false;
122
[6889]123      foreach (object o in intersections) {
124        string typeName = o.GetType().FullName;
125        if (excludedTypes.Contains(o.GetType())) {
[6921]126          //TestContext.WriteLine("Skipping excluded type " + typeName);
[6889]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;
[11782]129          if (!headerWritten) {
130            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
131            headerWritten = true;
132          }
[6889]133          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
134          success = false;
[11782]135        } else {
136          Array array = o as Array;
[11784]137          if (array != null && array.Length == 0) continue; //arrays of length 0 are used inside empty collections
[11782]138          if (!headerWritten) {
139            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
140            headerWritten = true;
141          }
[6889]142          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
[11782]143        }
[6889]144      }
145      return success;
146    }
147  }
148}
Note: See TracBrowser for help on using the repository browser.