Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17226 was 17226, checked in by mkommend, 5 years ago

#2521: Merged trunk changes into problem refactoring branch.

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