SvgTestHelper.cs 12.4 KB
Newer Older
1
2
3
4
5
6
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
7
using System.Text;
8
9
10
11
12
13
14
15
16
17
using System.Xml;

namespace Svg.UnitTests
{
    public abstract class SvgTestHelper
    {

        /// <summary>
        /// Test file path.
        /// </summary>
18
        [Obsolete("Try not to use the file loader, please use the resource loader to ensure working of tests on all systems")]
19
        protected virtual string TestFile
20
21
22
23
24
25
26
27
        {
            get
            {
                const string msg = "Test file not overridden.";
                Assert.Inconclusive(msg);
                throw new NotImplementedException(msg);
            }
        }
28

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

        /// <summary>
        /// Full Unit Test resource string for test file. 
        /// </summary>
        /// <remarks>
        /// For the full Unit Test resource string you can use <see cref="GetFullResourceString(string)"/>.
        /// </remarks>
        protected virtual string TestResource
        {
            get
            {
                const string msg = "Test resource not overridden.";
                Assert.Inconclusive(msg);
                throw new NotImplementedException(msg);
            }
        }


        /// <summary>
        /// Expected size of svg file after drawing.
        /// </summary>
        protected virtual int ExpectedSize
        {
            get
            {
                const string msg = "Expected size not overridden.";
                Assert.Inconclusive(msg);
                throw new NotImplementedException(msg);
            }
        }






        /// <summary>
        /// Get full Unit Test resource string.
        /// </summary>
        /// <param name="resourcePath">Resource path.</param>
        /// <returns>Full resource string.</returns>
        /// <example>
        /// var s = GetFullResourceString("Issue204_PrivateFont.Text.svg");
        /// // s content: "Svg.UnitTests.Resources.Issue204_PrivateFont.Text.svg"
        /// </example>
        protected virtual string GetFullResourceString(string resourcePath)
        {
            const string DefaultResourcesDir = "Resources";
77
            return string.Format("{0}.{1}.{2}",
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
                this.GetType().Assembly.GetName().Name,
                DefaultResourcesDir,
                resourcePath);
        }


        /// <summary>
        /// Get embedded resource as stream from Unit Test resources.
        /// </summary>
        /// <param name="fullResourceString">Full Unit Test resource string.</param>
        /// <returns>Embedded resource data steam.</returns>
        /// <remarks>Do not forget to close, dispose the stream.</remarks>
        protected virtual Stream GetResourceStream(string fullResourceString)
        {
            Trace.WriteLine("Get resource data.");
            var s = this.GetType().Assembly.GetManifestResourceStream(fullResourceString);
            if (s == null)
                Assert.Fail("Unable to find embedded resource", fullResourceString);
            Trace.WriteLine("Done getting resource data.");
            return s;
        }


        /// <summary>
        /// Get embedded resource as byte array from Unit Test resources.
        /// </summary>
        /// <param name="fullResourceString">Full Unit Test resource string.</param>
        /// <returns>Embedded resource data bytes.</returns>
        protected virtual byte[] GetResourceBytes(string fullResourceString)
        {
            using (var s = GetResourceStream(fullResourceString))
            {
                var resource = new byte[s.Length];
                s.Read(resource, 0, (int)s.Length);
                return resource;
            }
        }


        /// <summary>
        /// Get embedded resource as xml document from Unit Test resources.
        /// </summary>
        /// <param name="fullResourceString">Full Unit Test resource string.</param>
        /// <returns>Embedded resource data xml document.</returns>
        protected virtual XmlDocument GetResourceXmlDoc(string fullResourceString)
        {
            using (var s = GetResourceStream(fullResourceString))
            {
                Trace.WriteLine("Load XmlDocument from resource data.");
                var xmlDoc = new XmlDocument();
128
                xmlDoc.XmlResolver = new SvgDtdResolver();
129
130
131
132
                xmlDoc.Load(s);
                Trace.WriteLine("Done XmlDocument loading from resource data.");
                return xmlDoc;
            }
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        }

        /// <summary>
        /// Get embedded resource as string from Unit Test resources.
        /// </summary>
        /// <param name="fullResourceString">Full Unit Test resource string.</param>
        /// <returns>Embedded resource data xml as string.</returns>
        protected virtual string GetResourceXmlDocAsString(string fullResourceString)
        {
            using (var s = GetResourceStream(fullResourceString))
            {
                Trace.WriteLine("Load XmlDocument content from resource data.");
                using (var reader = new StreamReader(s, Encoding.UTF8))
                {
                    string value = reader.ReadToEnd();
                    Trace.WriteLine("Done XmlDocument content loading from resource data.");
                    return value;
                }
            }
152
153
154
155
156
157
        }

        /// <summary>
        /// Get xml document from <see cref="TestFile"/>.
        /// </summary>
        /// <returns>File data as xml document.</returns>
158
159
        [Obsolete("Try not to use the file loader, please use the resource loader to ensure working of tests on all systems")]
        protected virtual XmlDocument GetXMLDocFromFile()
160
161
162
163
164
165
166
167
168
169
        {
            return GetXMLDocFromFile(TestFile);
        }


        /// <summary>
        /// Get xml document from file.
        /// </summary>
        /// <param name="file">File to load.</param>
        /// <returns>File data as xml document.</returns>
170
171
        [Obsolete("Try not to use the file loader, please use the resource loader to ensure working of tests on all systems")]
        protected virtual XmlDocument GetXMLDocFromFile(string file)
172
        {
173
174
            if (!File.Exists(file))
                Assert.Fail("Test file missing.", file);
175
176
177
178

            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(File.ReadAllText(file));
            return xmlDoc;
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        }

        /// <summary>
        /// Get the xml document from an input string
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected virtual XmlDocument GetXMLDocFromString(string input)
        {
            Trace.WriteLine("Load XmlDocument from input data.");
            var xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = new SvgDtdResolver();
            xmlDoc.LoadXml(input);
            Trace.WriteLine("Done XmlDocument loading from resource data.");
            return xmlDoc;
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        }

        /// <summary>
        /// Get xml document from <see cref="TestResource"/>.
        /// </summary>
        /// <returns>Resource data as xml document.</returns>
        protected virtual XmlDocument GetXMLDocFromResource()
        {
            return GetResourceXmlDoc(TestResource);
        }


        /// <summary>
        /// Get xml document from resource.
        /// </summary>
        /// <param name="fullResourceString">Full Unit Test resource string.</param>
        /// <returns>Resource data as xml document.</returns>
        protected virtual XmlDocument GetXMLDocFromResource(string fullResourceString)
        {
            return GetResourceXmlDoc(fullResourceString);
        }


        /// <summary>
        /// Load, draw and check svg file.
        /// </summary>
        /// <param name="xml">Svg file data.</param>
        protected virtual void LoadSvg(XmlDocument xml)
        {
            Trace.WriteLine("SvgDocument open xml.");
HeinrichAD's avatar
HeinrichAD committed
224
            var svgDoc = OpenSvg(xml);
225
226
227
            Trace.WriteLine("Done SvgDocument open xml.");

            Trace.WriteLine("Draw svg.");
HeinrichAD's avatar
HeinrichAD committed
228
            var img = DrawSvg(svgDoc);
229
230
231
232
233
234
            Trace.WriteLine("Done drawing.");

            CheckSvg(svgDoc, img);
        }


HeinrichAD's avatar
HeinrichAD committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        /// <summary>
        /// Open SVG document from XML document.
        /// </summary>
        /// <param name="xml">XML document.</param>
        /// <returns>Open SVG document.</returns>
        protected virtual SvgDocument OpenSvg(XmlDocument xml)
        {
            return SvgDocument.Open(xml);
        }


        /// <summary>
        /// Draw SVG.
        /// </summary>
        /// <param name="svgDoc">SVG document to draw.</param>
        /// <returns>SVG as image.</returns>
        protected virtual Image DrawSvg(SvgDocument svgDoc)
        {
            return svgDoc.Draw();
        }


257
258
259
260
261
        /// <summary>
        /// Check svg file data.
        /// </summary>
        /// <param name="svgDoc">Svg document.</param>
        /// <param name="img">Image of svg file from <paramref name="svgDoc"/>.</param>
HeinrichAD's avatar
HeinrichAD committed
262
        protected virtual void CheckSvg(SvgDocument svgDoc, Image img)
263
264
265
        {
            using (var ms = new MemoryStream())
            {
266
                img.Save(ms, ImageFormat.Png);
267
                ms.Flush();
268
                Assert.IsTrue(ms.Length >= ExpectedSize, $"Svg file size {ms.Length} does not match expected minimum size (expected {ExpectedSize}).");
269
270
            }
        }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349


        /// <summary>
        /// Compare Images.
        /// </summary>
        /// <param name="img1">Image 1.</param>
        /// <param name="img2">Image 2.</param>
        /// <returns>If images are completely equal: true; otherwise: false</returns>
        protected virtual bool ImagesAreEqual(Bitmap img1, Bitmap img2)
        {
            float imgEqualPercentage; // To ignore.
            return ImagesAreEqual(img1, img2, out imgEqualPercentage);
        }


        /// <summary>
        /// Compare Images.
        /// </summary>
        /// <param name="img1">Image 1.</param>
        /// <param name="img2">Image 2.</param>
        /// <param name="imgEqualPercentage">Image equal value in percentage. 0.0% == completely unequal. 100.0% == completely equal.</param>
        /// <returns>If images are completely equal: true; otherwise: false</returns>
        protected virtual bool ImagesAreEqual(Bitmap img1, Bitmap img2, out float imgEqualPercentage)
        {
            Bitmap imgDiff; // To ignore.
            return ImagesAreEqual(img1, img2, out imgEqualPercentage, out imgDiff);
        }


        /// <summary>
        /// Compare Images.
        /// </summary>
        /// <param name="img1">Image 1.</param>
        /// <param name="img2">Image 2.</param>
        /// <param name="imgEqualPercentage">Image equal value in percentage. 0.0% == completely unequal. 100.0% == completely equal.</param>
        /// <param name="imgDiff">Image with red pixel where <paramref name="img1"/> and <paramref name="img2"/> are unequal.</param>
        /// <returns>If images are completely equal: true; otherwise: false</returns>
        protected virtual bool ImagesAreEqual(Bitmap img1, Bitmap img2, out float imgEqualPercentage, out Bitmap imgDiff)
        {
            // Defaults.
            var diffColor = Color.Red;

            // Reset.
            imgEqualPercentage = 0;
            imgDiff = null;

            // Requirements.
            if (img1 == null)
                return false;
            if (img2 == null)
                return false;
            if (img1.Size.Width < 1 && img1.Height < 1)
                return false;
            if (!img1.Size.Equals(img2.Size))
                return false;

            // Compare bitmaps.
            imgDiff = new Bitmap(img1.Size.Width, img1.Size.Height);
            int diffPixelCount = 0;
            for (int i = 0; i < img1.Width; ++i)
            {
                for (int j = 0; j < img1.Height; ++j)
                {
                    Color color;
                    if ((color = img1.GetPixel(i, j)) == img2.GetPixel(i, j))
                    {
                        imgDiff.SetPixel(i, j, color);
                    }
                    else
                    {
                        ++diffPixelCount;
                        imgDiff.SetPixel(i, j, diffColor);
                    }
                }
            }

            // Calculate percentage.
            int totalPixelCount = img1.Width * img1.Height;
            var imgDiffFactor = ((float)diffPixelCount / totalPixelCount);
350
351
            imgEqualPercentage = imgDiffFactor * 100;

352
353
            return (imgDiffFactor == 1f);
        }
354
355
    }
}