Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2936_GQAPIntegration/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 16824

Last change on this file since 16824 was 16711, checked in by gkronber, 6 years ago

#2936: merged r16117:16706 from trunk/HeuristicLab.Tests to branch/HeuristicLab.Tests

File size: 7.0 KB
RevLine 
[6889]1#region License Information
2/* HeuristicLab
[16711]3 * Copyright (C) 2002-2019 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);
[14209]55      // SimpleSymbol is a non-discoverable type and thus needs to be added manually
56      excludedTypes.Add(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SimpleSymbol));
[6921]57      foreach (var grammarType in ApplicationManager.Manager.GetTypes(typeof(HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.SymbolicExpressionGrammarBase)))
58        excludedTypes.Add(grammarType);
[6889]59    }
60
61    private readonly HashSet<Type> excludedTypes;
62
63    [TestMethod]
[9783]64    [TestCategory("General")]
65    [TestCategory("Essential")]
66    [TestProperty("Time", "long")]
[6889]67    public void TestCloningFinishedExperiment() {
[9955]68      Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl");
[6889]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]
[9783]77    [TestCategory("General")]
78    [TestCategory("Essential")]
79    [TestProperty("Time", "long")]
[6889]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);
[12722]94        } catch { continue; } // no default constructor
[6889]95
[8046]96        IDeepCloneable clone = null;
97        try {
98          clone = (IDeepCloneable)item.Clone(new Cloner());
[12722]99        } catch (Exception e) {
[8052]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!");
[8046]103          success = false;
104          continue;
105        }
[6889]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) {
[7467]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());
[6889]118
[8078]119      return originalObjects.Intersect(clonedObjects, new ReferenceEqualityComparer());
[6889]120    }
121
122    private bool ProcessEqualObjects(IDeepCloneable item, IEnumerable<object> intersections) {
123      bool success = true;
[11782]124      bool headerWritten = false;
125
[6889]126      foreach (object o in intersections) {
127        string typeName = o.GetType().FullName;
128        if (excludedTypes.Contains(o.GetType())) {
[6921]129          //TestContext.WriteLine("Skipping excluded type " + typeName);
[6889]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;
[11782]132          if (!headerWritten) {
133            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
134            headerWritten = true;
135          }
[6889]136          TestContext.WriteLine("POTENTIAL ERROR! A DEEPCLONEABLE WAS NOT DEEP CLONED (" + info + "): " + typeName);
137          success = false;
[11782]138        } else {
139          Array array = o as Array;
[11784]140          if (array != null && array.Length == 0) continue; //arrays of length 0 are used inside empty collections
[11782]141          if (!headerWritten) {
142            TestContext.WriteLine(Environment.NewLine + item.GetType().FullName + ":");
143            headerWritten = true;
144          }
[6889]145          TestContext.WriteLine("WARNING: An object of type " + typeName + " is referenced in the original and in the clone.");
[11782]146        }
[6889]147      }
148      return success;
149    }
150  }
151}
Note: See TracBrowser for help on using the repository browser.