Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2520_PersistenceReintegration/HeuristicLab.Tests/HeuristicLab.Persistence.Attic/UseCases.cs @ 16713

Last change on this file since 16713 was 16559, checked in by jkarder, 6 years ago

#2520: renamed Fossil to Attic and set version to 1.0.0-pre01

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