Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 16674

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

#2221: integrated PTSP 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        typeof (HeuristicLab.Problems.PTSP.DistanceMatrix)
50      };
51      excludedTypes.Add(typeof(SymbolicExpressionGrammar).Assembly.GetType("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.EmptySymbolicExpressionTreeGrammar"));
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);
57    }
58
59    private readonly HashSet<Type> excludedTypes;
60
61    [TestMethod]
62    [TestCategory("General")]
63    [TestCategory("Essential")]
64    [TestProperty("Time", "long")]
65    public void TestCloningFinishedExperiment() {
66      Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl");
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]
75    [TestCategory("General")]
76    [TestCategory("Essential")]
77    [TestProperty("Time", "long")]
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);
92        } catch { continue; } // no default constructor
93
94        IDeepCloneable clone = null;
95        try {
96          clone = (IDeepCloneable)item.Clone(new Cloner());
97        } catch (Exception e) {
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!");
101          success = false;
102          continue;
103        }
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) {
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());
116
117      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
118    }
119
120    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
121      bool success = true;
122      bool headerWritten = false;
123
124      foreach (object o in intersections) {
125        string typeName = o.GetType().FullName;
126        if (excludedTypes.Contains(o.GetType())) {
127          //TestContext.WriteLine("Skipping excluded type " + typeName);
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;
130          if (!headerWritten) {
131            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
132            headerWritten = true;
133          }
134          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
135          success = false;
136        } else {
137          Array array = o as Array;
138          if (array != null && array.Length == 0) continue; //arrays of length 0 are used inside empty collections
139          if (!headerWritten) {
140            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
141            headerWritten = true;
142          }
143          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
144        }
145      }
146      return success;
147    }
148  }
149}
Note: See TracBrowser for help on using the repository browser.