Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Tests/HeuristicLab.Persistence.Attic/UseCases.cs @ 16578

Last change on this file since 16578 was 16578, checked in by gkronber, 4 years ago

#2520: changed unit tests which load old samples and try storing and loading using the new format to recreate all sample files first

File size: 9.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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.Drawing;
25using System.IO;
26using System.Linq;
27using System.Reflection;
28using System.Threading.Tasks;
29using HEAL.Attic;
30using HeuristicLab.Algorithms.GeneticAlgorithm;
31using HeuristicLab.Analysis;
32using HeuristicLab.Common;
33using HeuristicLab.Core;
34using HeuristicLab.Data;
35using HeuristicLab.Persistence.Core;
36using HeuristicLab.Persistence.Default.Xml;
37using HeuristicLab.Tests;
38using Microsoft.VisualStudio.TestTools.UnitTesting;
39
40namespace HeuristicLab.Persistence.Attic.Tests {
41  [TestClass]
42  public class UseCases {
43
44    private string tempFile;
45
46    [TestInitialize()]
47    public void CreateTempFile() {
48      tempFile = Path.GetTempFileName();
49    }
50
51    [TestCleanup()]
52    public void ClearTempFile() {
53      StreamReader reader = new StreamReader(tempFile);
54      string s = reader.ReadToEnd();
55      reader.Close();
56      File.Delete(tempFile);
57    }
58
59    [TestMethod]
60    [TestCategory("Persistence.Attic")]
61    [TestProperty("Time", "short")]
62    public void BitmapTest() {
63      Icon icon = System.Drawing.SystemIcons.Hand;
64      Bitmap bitmap = icon.ToBitmap();
65      new ProtoBufSerializer().Serialize(bitmap, tempFile);
66      Bitmap newBitmap = (Bitmap)new ProtoBufSerializer().Deserialize(tempFile);
67
68      Assert.AreEqual(bitmap.Size, newBitmap.Size);
69      for (int i = 0; i < bitmap.Size.Width; i++)
70        for (int j = 0; j < bitmap.Size.Height; j++)
71          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
72    }
73
74
75    [TestMethod]
76    [TestCategory("Persistence.Attic")]
77    [TestProperty("Time", "short")]
78    public void FontTest() {
79      List<Font> fonts = new List<Font>() {
80        new Font(FontFamily.GenericSansSerif, 12),
81        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
82        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
83        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
84      };
85      new ProtoBufSerializer().Serialize(fonts, tempFile);
86      var newFonts = (List<Font>)new ProtoBufSerializer().Deserialize(tempFile);
87      Assert.AreEqual(fonts[0], newFonts[0]);
88      Assert.AreEqual(fonts[1], newFonts[1]);
89      Assert.AreEqual(fonts[2], newFonts[2]);
90      Assert.AreEqual(fonts[3], newFonts[3]);
91    }
92
93    [TestMethod]
94    [TestCategory("Persistence.Attic")]
95    [TestProperty("Time", "medium")]
96    public void ConcurrencyTest() {
97      int n = 20;
98      Task[] tasks = new Task[n];
99      for (int i = 0; i < n; i++) {
100        tasks[i] = Task.Factory.StartNew((idx) => {
101          byte[] data;
102          using (var stream = new MemoryStream()) {
103            new ProtoBufSerializer().Serialize(new GeneticAlgorithm(), stream);
104            data = stream.ToArray();
105          }
106        }, i);
107      }
108      Task.WaitAll(tasks);
109    }
110
111    [TestMethod]
112    [TestCategory("Persistence.Attic")]
113    [TestProperty("Time", "medium")]
114    public void ConcurrentBitmapTest() {
115      Bitmap b = new Bitmap(300, 300);
116      System.Random r = new System.Random();
117      for (int x = 0; x < b.Height; x++) {
118        for (int y = 0; y < b.Width; y++) {
119          b.SetPixel(x, y, Color.FromArgb(r.Next()));
120        }
121      }
122      Task[] tasks = new Task[20];
123      byte[][] datas = new byte[tasks.Length][];
124      for (int i = 0; i < tasks.Length; i++) {
125        tasks[i] = Task.Factory.StartNew((idx) => {
126          using (var stream = new MemoryStream()) {
127            new ProtoBufSerializer().Serialize(b, stream);
128            datas[(int)idx] = stream.ToArray();
129          }
130        }, i);
131      }
132      Task.WaitAll(tasks);
133    }
134
135    private void CreateAllSamples() {
136      var asm = this.GetType().Assembly;
137      foreach (var t in asm.GetTypes()) {
138        var attrs = t.GetCustomAttributes<TestClassAttribute>();
139        if (attrs.Any()) {
140          try {
141            var testObj = Activator.CreateInstance(t);
142            foreach (var mi in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
143              var mAttrs = mi.GetCustomAttributes<TestCategoryAttribute>();
144              var testCategories = mAttrs.SelectMany(mattr => mattr.TestCategories);
145              if (testCategories.Any(tc => tc == "Samples.Create")) {
146                mi.Invoke(testObj, new object[0]);
147              }
148            }
149          } catch (Exception) { }
150        }
151      }
152    }
153
154    [TestMethod]
155    [TestCategory("Persistence.Attic")]
156    [TestProperty("Time", "long")]
157    public void TestLoadingSamples() {
158      CreateAllSamples();
159      var path = SamplesUtils.SamplesDirectory;
160      var serializer = new ProtoBufSerializer();
161      foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
162        var original = XmlParser.Deserialize(fileName);
163        var ok = true;
164        foreach (var t in original.GetObjectGraphObjects().Select(o => o.GetType())) {
165          if (
166            t.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
167              .Any(ctor => StorableConstructorAttribute.IsStorableConstructor(ctor))) {
168            try {
169              if (t.IsGenericType) {
170                var g = Mapper.StaticCache.GetGuid(t.GetGenericTypeDefinition());
171              } else {
172                var g = Mapper.StaticCache.GetGuid(t);
173              }
174            } catch (Exception e) {
175              Console.WriteLine($"type {t.FullName} in {fileName} is not registered with a GUID in HEAL.Attic");
176              ok = false;
177            }
178          }
179        }
180        if (ok) {
181          serializer.Serialize(original, fileName + ".proto");
182          var newVersion = serializer.Deserialize(fileName + ".proto");
183          Console.WriteLine("File: " + fileName);
184          File.Delete(fileName + ".proto");
185        }
186      }
187    }
188
189    [TestMethod]
190    [TestCategory("Persistence.Attic")]
191    [TestProperty("Time", "long")]
192    public void TestLoadingRunAndStoreSamples() {
193      CreateAllSamples();
194      var path = SamplesUtils.SamplesDirectory;
195      var serializer = new ProtoBufSerializer();
196      foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
197        var original = XmlParser.Deserialize(fileName);
198
199        var exec = original as IExecutable;
200        if (exec != null) {
201          exec.Paused += (sender, e) => {
202            serializer.Serialize(exec, fileName + "_paused.proto");
203            Console.WriteLine("Serialized paused file: " + fileName);
204            File.Delete(fileName + "_paused.proto");
205          };
206          exec.Stopped += (sender, e) => {
207            serializer.Serialize(exec, fileName + "_stopped.proto");
208            Console.WriteLine("Serialized stopped file: " + fileName);
209            File.Delete(fileName + "_stopped.proto");
210          };
211          var t = exec.StartAsync();
212          System.Threading.Thread.Sleep(20000); // wait 20 secs
213          if (exec.ExecutionState == ExecutionState.Started) { // only if not already stopped
214            exec.Pause();
215          }
216        }
217      }
218    }
219
220
221    [TestMethod]
222    [TestCategory("Persistence.Attic")]
223    [TestProperty("Time", "short")]
224    public void TestIndexedDataTable() {
225      var dt = new IndexedDataTable<int>("test", "test description");
226      var dr = new IndexedDataRow<int>("test row");
227      dr.Values.Add(Tuple.Create(1, 1.0));
228      dr.Values.Add(Tuple.Create(2, 2.0));
229      dr.Values.Add(Tuple.Create(3, 3.0));
230      dt.Rows.Add(dr);
231      var ser = new ProtoBufSerializer();
232      ser.Serialize(dt, tempFile);
233      var dt2 = (IndexedDataTable<int>)ser.Deserialize(tempFile);
234      Assert.AreEqual(dt.Rows["test row"].Values[0], dt2.Rows["test row"].Values[0]);
235      Assert.AreEqual(dt.Rows["test row"].Values[1], dt2.Rows["test row"].Values[1]);
236      Assert.AreEqual(dt.Rows["test row"].Values[2], dt2.Rows["test row"].Values[2]);
237    }
238
239    [TestMethod]
240    [TestCategory("Persistence.Attic")]
241    [TestProperty("Time", "short")]
242    public void TestPoint2d() {
243      var tag = new IntValue(10);
244      var p = new Point2D<double>(1.0, 2.0, tag);
245      var ser = new ProtoBufSerializer();
246      ser.Serialize(p, tempFile);
247      var p2 = (Point2D<double>)ser.Deserialize(tempFile);
248      Assert.AreEqual(p.X, p2.X);
249      Assert.AreEqual(p.Y, p2.Y);
250      var tag2 = (IntValue)p2.Tag;
251      Assert.AreEqual(tag.Value, tag2.Value);
252    }
253
254    [ClassInitialize]
255    public static void Initialize(TestContext testContext) {
256      ConfigurationService.Instance.Reset();
257    }
258  }
259}
Note: See TracBrowser for help on using the repository browser.