Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 18242

Last change on this file since 18242 was 17696, checked in by abeham, 4 years ago

#2521:

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