Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Tests/HeuristicLab-3.3/DeepCloneableCloningTest.cs @ 11514

Last change on this file since 11514 was 11514, checked in by jkarder, 8 years ago

#2211:

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