Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 11874

Last change on this file since 11874 was 11874, checked in by mkommend, 9 years ago

#2268: Merged r11494, r11495, r11496, r11497, r11498, r11504, r11532, r11536 into stable.

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