Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17543 was 17543, checked in by mkommend, 4 years ago

#2521: Merged trunk changes into branch (+ corrected type in unit test).

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