Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 14521

Last change on this file since 14521 was 14477, checked in by abeham, 8 years ago

#2701:

  • Added TryGetBy(First|Second) method to BidirectionalDictionary
  • Updated linear linkage encoding
    • Added move generator and moves for shift, merge, split, and extract moves
    • Added unit test (Apply/Undo)
  • Updated MemPR (linear linkage)
    • Added basic tabu walk
  • Fixed bug in MemPR (permutation)
  • Updated Tests project
File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 (global::HeuristicLab.Problems.DataAnalysis.Dataset),
45        typeof (global::HeuristicLab.Problems.TravelingSalesman.DistanceMatrix),
46        typeof (global::HeuristicLab.Problems.DataAnalysis.ClassificationEnsembleSolution),
47        typeof (global::HeuristicLab.Problems.DataAnalysis.RegressionEnsembleSolution),
48        typeof (global::HeuristicLab.Problems.Orienteering.DistanceMatrix),
49        typeof (global::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(global::HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbol)))
54        excludedTypes.Add(symbolType);
55      // SimpleSymbol is a non-discoverable type and thus needs to be added manually
56      excludedTypes.Add(typeof(global::HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SimpleSymbol));
57      foreach (var grammarType in ApplicationManager.Manager.GetTypes(typeof(global::HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SymbolicExpressionGrammarBase)))
58        excludedTypes.Add(grammarType);
59    }
60
61    private readonly HashSet<Type> excludedTypes;
62
63    [TestMethod]
64    [TestCategory("General")]
65    [TestCategory("Essential")]
66    [TestProperty("Time", "long")]
67    public void TestCloningFinishedExperiment() {
68      Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl");
69
70      Experiment clone = (Experiment)experiment.Clone(new Cloner());
71      var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
72
73      Assert.IsTrue(ProcessEqualObjects(experiment, intersections));
74    }
75
76    [TestMethod]
77    [TestCategory("General")]
78    [TestCategory("Essential")]
79    [TestProperty("Time", "long")]
80    public void TestCloningAllDeepCloneables() {
81      PluginLoader.Assemblies.ToArray();
82      bool success = true;
83      foreach (Type deepCloneableType in ApplicationManager.Manager.GetTypes(typeof(IDeepCloneable))) {
84        // skip types that explicitely choose not to deep-clone every member
85        if (excludedTypes.Contains(deepCloneableType)) continue;
86        // test only types contained in HL plugin assemblies
87        if (!PluginLoader.Assemblies.Contains(deepCloneableType.Assembly)) continue;
88        // test only instantiable types
89        if (deepCloneableType.IsAbstract || !deepCloneableType.IsClass) continue;
90
91        IDeepCloneable item = null;
92        try {
93          item = (IDeepCloneable)Activator.CreateInstance(deepCloneableType, nonPublic: false);
94        } catch { continue; } // no default constructor
95
96        IDeepCloneable clone = null;
97        try {
98          clone = (IDeepCloneable)item.Clone(new Cloner());
99        } catch (Exception e) {
100          TestContext.WriteLine(Environment.NewLine + deepCloneableType.FullName + ":");
101          TestContext.WriteLine("ERROR! " + e.GetType().Name + @" was thrown during cloning.
102All IDeepCloneable items with a default constructor should be cloneable when using that constructor!");
103          success = false;
104          continue;
105        }
106        var intersections = CheckTotalInequality(item, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab"));
107        if (!intersections.Any()) continue;
108
109        if (!ProcessEqualObjects(item, intersections))
110          success = false;
111      }
112      Assert.IsTrue(success, "There are potential errors in deep cloning objects.");
113    }
114
115    private IEnumerable<object> CheckTotalInequality(object original, object clone) {
116      var originalObjects = new HashSet<object>(original.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
117      var clonedObjects = new HashSet<object>(clone.GetObjectGraphObjects(excludeStaticMembers: true).Where(x => !x.GetType().IsValueType), new ReferenceEqualityComparer());
118
119      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
120    }
121
122    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
123      bool success = true;
124      bool headerWritten = false;
125
126      foreach (object o in intersections) {
127        string typeName = o.GetType().FullName;
128        if (excludedTypes.Contains(o.GetType())) {
129          //TestContext.WriteLine("Skipping excluded type " + typeName);
130        } else if (o is IDeepCloneable) {
131          string info = (o is IItem) ? ((IItem)o).ItemName + ((o is INamedItem) ? ", " + ((INamedItem)o).Name : String.Empty) : String.Empty;
132          if (!headerWritten) {
133            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
134            headerWritten = true;
135          }
136          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
137          success = false;
138        } else {
139          Array array = o as Array;
140          if (array != null && array.Length == 0) continue; //arrays of length 0 are used inside empty collections
141          if (!headerWritten) {
142            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
143            headerWritten = true;
144          }
145          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
146        }
147      }
148      return success;
149    }
150  }
151}
Note: See TracBrowser for help on using the repository browser.