-
Notifications
You must be signed in to change notification settings - Fork 696
/
ImageAssert.cs
389 lines (326 loc) · 16.5 KB
/
ImageAssert.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
77
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#nullable enable
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;
using SamplesApp.UITests._Utils;
using Uno.UITest;
using static System.Math;
namespace SamplesApp.UITests.TestFramework
{
public static partial class ImageAssert
{
private static bool IgnoreImageAsserts { get; } = false;
static ImageAssert()
{
// Provides the ability to mark as ignored tests using ImageAssert.
// See https://github.com/unoplatform/uno/issues/9550
if (bool.TryParse(Environment.GetEnvironmentVariable("UNO_UITEST_IGNORE_IMAGEASSERTS"), out var ignoreImageAsserts))
{
IgnoreImageAsserts = ignoreImageAsserts;
}
}
public static Rectangle FirstQuadrant { get; } = new Rectangle(0, 0, int.MaxValue, int.MaxValue);
#region Are[Almost]Equal
public static void AreEqual(ScreenshotInfo expected, ScreenshotInfo actual, IAppRect rect, double expectedToActualScale = 1, PixelTolerance tolerance = default, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, rect.ToRectangle(), actual, rect.ToRectangle(), expectedToActualScale, tolerance, line);
public static void AreEqual(ScreenshotInfo expected, ScreenshotInfo actual, Rectangle? rect = null, double expectedToActualScale = 1, PixelTolerance tolerance = default, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, rect ?? FirstQuadrant, actual, rect ?? FirstQuadrant, expectedToActualScale, tolerance, line);
public static void AreEqual(ScreenshotInfo expected, IAppRect expectedRect, ScreenshotInfo actual, IAppRect actualRect, double expectedToActualScale = 1, PixelTolerance tolerance = default, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect.ToRectangle(), actual, actualRect.ToRectangle(), expectedToActualScale, tolerance, line);
public static void AreEqual(ScreenshotInfo expected, Rectangle expectedRect, ScreenshotInfo actual, Rectangle actualRect, double expectedToActualScale = 1, PixelTolerance tolerance = default, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect, actual, actualRect, expectedToActualScale, tolerance, line);
/// <summary>
/// Asserts that two screenshots are equal to each other inside the area of the nominated rect to within the given pixel error
/// (ie, the A, R, G, or B values cumulatively differ by more than the permitted error for any pixel).
/// </summary>
public static void AreAlmostEqual(ScreenshotInfo expected, ScreenshotInfo actual, IAppRect rect, int permittedPixelError, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, rect.ToRectangle(), actual, rect.ToRectangle(), expectedToActualScale, PixelTolerance.Cummulative(permittedPixelError), line);
/// <summary>
/// Asserts that two screenshots are equal to each other inside the area of the nominated rect to within the given pixel error
/// (ie, the A, R, G, or B values cumulatively differ by more than the permitted error for any pixel).
/// </summary>
public static void AreAlmostEqual(ScreenshotInfo expected, ScreenshotInfo actual, Rectangle? rect = null, int permittedPixelError = 5, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, rect ?? FirstQuadrant, actual, rect ?? FirstQuadrant, expectedToActualScale, PixelTolerance.Cummulative(permittedPixelError), line);
/// <summary>
/// Asserts that two screenshots are equal to each other inside the area of the nominated rect to within the given pixel error
/// (ie, the A, R, G, or B values cumulatively differ by more than the permitted error for any pixel).
/// </summary>
public static void AreAlmostEqual(ScreenshotInfo expected, IAppRect expectedRect, ScreenshotInfo actual, IAppRect actualRect, int permittedPixelError, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect.ToRectangle(), actual, actualRect.ToRectangle(), expectedToActualScale, PixelTolerance.Cummulative(permittedPixelError), line);
/// <summary>
/// Asserts that two screenshots are equal to each other inside the area of the nominated rect to within the given pixel error
/// (ie, the A, R, G, or B values cumulatively differ by more than the permitted error for any pixel).
/// </summary>
public static void AreAlmostEqual(ScreenshotInfo expected, Rectangle expectedRect, ScreenshotInfo actual, Rectangle actualRect, int permittedPixelError, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect, actual, actualRect, expectedToActualScale, PixelTolerance.Cummulative(permittedPixelError), line);
/// <summary>
/// Asserts that two screenshots are equal to each other inside the area of the nominated rect to within the given pixel error
/// (ie, the A, R, G, or B values cumulatively differ by more than the permitted error for any pixel).
/// </summary>
public static void AreAlmostEqual(ScreenshotInfo expected, Rectangle expectedRect, ScreenshotInfo actual, Rectangle actualRect, double expectedToActualScale, PixelTolerance tolerance, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect, actual, actualRect, expectedToActualScale, tolerance, line);
public static void AreAlmostEqual(ScreenshotInfo expected, Rectangle expectedRect, Bitmap actual, Rectangle actualRect, double expectedToActualScale, PixelTolerance tolerance, [CallerLineNumber] int line = 0)
=> AreEqualImpl(expected, expectedRect, null, actual, actualRect, expectedToActualScale, tolerance, line);
private static void AreEqualImpl(
ScreenshotInfo expected,
Rectangle expectedRect,
ScreenshotInfo actual,
Rectangle actualRect,
double expectedToActualScale,
PixelTolerance tolerance,
[CallerLineNumber] int line = 0)
{
TryIgnoreImageAssert();
var actualBitmap = actual.GetBitmap();
AreEqualImpl(expected, expectedRect, actual, actualBitmap, actualRect, expectedToActualScale, tolerance, line);
}
private static void AreEqualImpl(
ScreenshotInfo expected,
Rectangle expectedRect,
ScreenshotInfo? actual,
Bitmap actualBitmap,
Rectangle actualRect,
double expectedToActualScale,
PixelTolerance tolerance,
[CallerLineNumber] int line = 0)
{
TryIgnoreImageAssert();
using var assertionScope = new AssertionScope($"{expected.StepName}<=={actual}");
assertionScope.AddReportable("expectedRect", expectedRect.ToString());
assertionScope.AddReportable("actualRect", actualRect.ToString());
assertionScope.AddReportable("expectedToActualScale", expectedToActualScale.ToString(NumberFormatInfo.InvariantInfo));
var (areEqual, context) = EqualityCheck(expected, expectedRect, actual, actualBitmap, actualRect, expectedToActualScale, tolerance, line);
if (areEqual)
{
Console.WriteLine(context.ToString());
}
else
{
assertionScope.FailWithText(context);
}
}
private static (bool areEqual, string context) EqualityCheck(
ScreenshotInfo expected,
Rectangle expectedRect,
ScreenshotInfo? actual,
Bitmap actualBitmap,
Rectangle actualRect,
double expectedToActualScale,
PixelTolerance tolerance,
[CallerLineNumber] int line = 0)
{
TryIgnoreImageAssert();
var expectedBitmap = expected.GetBitmap();
if (expectedRect != FirstQuadrant && actualRect != FirstQuadrant)
{
Assert.AreEqual(expectedRect.Size, actualRect.Size, WithContext("Compare rects don't have the same size"));
}
if (expectedRect == FirstQuadrant && actualRect == FirstQuadrant)
{
var effectiveExpectedBitmapSize = new Size(
(int)(expectedBitmap.Size.Width * expectedToActualScale),
(int)(expectedBitmap.Size.Height * expectedToActualScale));
Assert.AreEqual(effectiveExpectedBitmapSize, actualBitmap.Size, WithContext("Screenshots don't have the same size"));
}
expectedRect = Normalize(expectedRect, expectedBitmap.Size);
actualRect = Normalize(actualRect, actualBitmap.Size);
var expectedPixels = ExpectedPixels
.At(actualRect.Location)
.Pixels(expectedBitmap, expectedRect)
.Named(expected.StepName)
.WithTolerance(tolerance);
var report = GetContext();
var result = Validate(expectedPixels, actualBitmap, expectedToActualScale, report);
return (result, report.ToString());
StringBuilder GetContext()
=> new StringBuilder()
.AppendLine($"ImageAssert.AreEqual @ line {line}")
.AppendLine("pixelTolerance: " + tolerance)
.AppendLine($"expected: {expected?.StepName} ({expected?.File.Name} {expectedBitmap.Size}){(expectedRect == FirstQuadrant ? null : $" in {expectedRect}")}")
.AppendLine($"actual : {actual?.StepName ?? "--unknown--"} ({actual?.File.Name} {actualBitmap.Size}){(actualRect == FirstQuadrant ? null : $" in {actualRect}")}")
.AppendLine("====================");
string WithContext(string message)
=> GetContext()
.AppendLine(message)
.ToString();
}
#endregion
#region AreNotEqual
public static void AreNotEqual(ScreenshotInfo expected, ScreenshotInfo actual, IAppRect rect, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreNotEqualImpl(expected, rect.ToRectangle(), actual, rect.ToRectangle(), expectedToActualScale, PixelTolerance.None, line);
public static void AreNotEqual(ScreenshotInfo expected, ScreenshotInfo actual, Rectangle? rect = null, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreNotEqualImpl(expected, rect ?? FirstQuadrant, actual, rect ?? FirstQuadrant, expectedToActualScale, PixelTolerance.None, line);
public static void AreNotEqual(ScreenshotInfo expected, IAppRect expectedRect, ScreenshotInfo actual, IAppRect actualRect, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreNotEqualImpl(expected, expectedRect.ToRectangle(), actual, actualRect.ToRectangle(), expectedToActualScale, PixelTolerance.None, line);
public static void AreNotEqual(ScreenshotInfo expected, Rectangle expectedRect, ScreenshotInfo actual, Rectangle actualRect, double expectedToActualScale = 1, [CallerLineNumber] int line = 0)
=> AreNotEqualImpl(expected, expectedRect, actual, actualRect, expectedToActualScale, PixelTolerance.None, line);
private static void AreNotEqualImpl(
ScreenshotInfo expected,
Rectangle expectedRect,
ScreenshotInfo actual,
Rectangle actualRect,
double expectedToActualScale,
PixelTolerance tolerance,
int line)
{
var actualBitmap = actual.GetBitmap();
AreNotEqualImpl(expected, expectedRect, actual, actualBitmap, actualRect, expectedToActualScale, tolerance, line);
}
private static void AreNotEqualImpl(
ScreenshotInfo expected,
Rectangle expectedRect,
ScreenshotInfo actual,
Bitmap actualBitmap,
Rectangle actualRect,
double expectedToActualScale,
PixelTolerance tolerance,
int line)
{
TryIgnoreImageAssert();
var result = EqualityCheck(expected, expectedRect, actual, actualBitmap, actualRect, expectedToActualScale, tolerance, line);
if (!result.areEqual)
{
Console.WriteLine(result.context);
}
else
{
AssertionScope.Current.FailWithText(result.context);
}
}
#endregion
#region HasColorAt
public static void HasColorAt(ScreenshotInfo screenshot, float x, float y, string expectedColorCode, byte tolerance = 0, double scale = 1.0, [CallerLineNumber] int line = 0)
=> HasColorAtImpl(screenshot, (int)x, (int)y, ColorCodeParser.Parse(expectedColorCode), tolerance, scale, line);
public static void HasColorAt(ScreenshotInfo screenshot, float x, float y, Color expectedColor, byte tolerance = 0, double scale = 1.0, [CallerLineNumber] int line = 0)
=> HasColorAtImpl(screenshot, (int)x, (int)y, expectedColor, tolerance, scale, line);
/// <summary>
/// Asserts that a given screenshot has a color anywhere at a given rectangle.
/// </summary>
public static void HasColorInRectangle(ScreenshotInfo screenshot, Rectangle rect, Color expectedColor, byte tolerance = 0, [CallerLineNumber] int line = 0)
{
TryIgnoreImageAssert();
var bitmap = screenshot.GetBitmap();
for (var x = rect.Left; x < rect.Right; x++)
{
for (var y = rect.Top; y < rect.Bottom; y++)
{
var pixel = bitmap.GetPixel(x, y);
if (AreSameColor(expectedColor, pixel, tolerance, out _))
{
return;
}
}
}
Assert.Fail($"Expected '{ToArgbCode(expectedColor)}' in rectangle '{rect}'.");
}
private static void HasColorAtImpl(ScreenshotInfo screenshot, int x, int y, Color expectedColor, byte tolerance, double scale, int line)
{
TryIgnoreImageAssert();
var bitmap = screenshot.GetBitmap();
x = (int)(x * scale);
y = (int)(y * scale);
if (bitmap.Width <= x || bitmap.Height <= y)
{
Assert.Fail(WithContext($"Coordinates ({x}, {y}) falls outside of screenshot dimension {bitmap.Size}"));
}
var pixel = bitmap.GetPixel(x, y);
if (!AreSameColor(expectedColor, pixel, tolerance, out var difference))
{
Assert.Fail(WithContext(builder: builder => builder
.AppendLine($"Color at ({x},{y}) is not expected")
.AppendLine($"expected: {ToArgbCode(expectedColor)} {expectedColor}")
.AppendLine($"actual : {ToArgbCode(pixel)} {pixel}")
.AppendLine($"tolerance: {tolerance}")
.AppendLine($"difference: {difference}")
));
}
string WithContext(string? message = null, Action<StringBuilder>? builder = null)
{
return new StringBuilder()
.AppendLine($"ImageAssert.HasColorAt @ line {line}")
.AppendLine($"screenshot: {screenshot.StepName} ({screenshot.File.Name})")
.AppendLine("====================")
.ApplyIf(message != null, sb => sb.AppendLine(message))
.ApplyIf(builder != null, builder)
.ToString();
}
}
#endregion
#region DoesNotHaveColorAt
public static void DoesNotHaveColorAt(ScreenshotInfo screenshot, float x, float y, string excludedColorCode, byte tolerance = 0, [CallerLineNumber] int line = 0)
=> DoesNotHaveColorAtImpl(screenshot, (int)x, (int)y, ColorCodeParser.Parse(excludedColorCode), tolerance, line);
public static void DoesNotHaveColorAt(ScreenshotInfo screenshot, float x, float y, Color excludedColor, byte tolerance = 0, [CallerLineNumber] int line = 0)
=> DoesNotHaveColorAtImpl(screenshot, (int)x, (int)y, excludedColor, tolerance, line);
private static void DoesNotHaveColorAtImpl(ScreenshotInfo screenshot, int x, int y, Color excludedColor, byte tolerance, int line)
{
TryIgnoreImageAssert();
var bitmap = screenshot.GetBitmap();
if (bitmap.Width <= x || bitmap.Height <= y)
{
Assert.Fail(WithContext($"Coordinates ({x}, {y}) falls outside of screenshot dimension {bitmap.Size}"));
}
var pixel = bitmap.GetPixel(x, y);
if (AreSameColor(excludedColor, pixel, tolerance, out var difference))
{
Assert.Fail(WithContext(builder: builder => builder
.AppendLine($"Color at ({x},{y}) is not expected")
.AppendLine($"excluded: {ToArgbCode(excludedColor)} {excludedColor.Name}")
.AppendLine($"actual : {ToArgbCode(pixel)} {pixel}")
.AppendLine($"tolerance: {tolerance}")
.AppendLine($"difference: {difference}")
));
}
string WithContext(string? message = null, Action<StringBuilder>? builder = null)
{
return new StringBuilder()
.AppendLine($"ImageAssert.DoesNotHaveColorAt @ line {line}")
.AppendLine($"screenshot: {screenshot.StepName} ({screenshot.File.Name})")
.AppendLine("====================")
.ApplyIf(message != null, sb => sb.AppendLine(message))
.ApplyIf(builder != null, builder)
.ToString();
}
}
#endregion
#region HasPixels
public static void HasPixels(ScreenshotInfo actual, params ExpectedPixels[] expectations)
{
TryIgnoreImageAssert();
var bitmap = actual.GetBitmap();
using var assertionScope = new AssertionScope("ImageAssert");
foreach (var expectation in expectations)
{
var x = expectation.Location.X;
var y = expectation.Location.Y;
Assert.GreaterOrEqual(bitmap.Width, x);
Assert.GreaterOrEqual(bitmap.Height, y);
var result = new StringBuilder();
result.AppendLine(expectation.Name);
if (!Validate(expectation, bitmap, 1, result))
{
assertionScope.FailWith(result.ToString());
}
}
}
#endregion
/// <summary>
/// See https://github.com/unoplatform/uno/issues/9550
/// </summary>
internal static void TryIgnoreImageAssert()
{
if (IgnoreImageAsserts)
{
Assert.Ignore("UNO_UITEST_IGNORE_IMAGEASSERTS was set, ignoring test which uses ImageAssert");
}
}
}
}