TestBase.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System.IO;
  4. using System.Runtime.CompilerServices;
  5. using ImageMagick;
  6. using Avalonia.Controls;
  7. using Avalonia.Media.Imaging;
  8. using Avalonia.Rendering;
  9. using Xunit;
  10. #if AVALONIA_CAIRO
  11. using Avalonia.Cairo;
  12. #elif AVALONIA_SKIA
  13. using Avalonia.Skia;
  14. #else
  15. using Avalonia.Direct2D1;
  16. #endif
  17. #if AVALONIA_CAIRO
  18. namespace Avalonia.Cairo.RenderTests
  19. #elif AVALONIA_SKIA
  20. namespace Avalonia.Skia.RenderTests
  21. #else
  22. namespace Avalonia.Direct2D1.RenderTests
  23. #endif
  24. {
  25. public class TestBase
  26. {
  27. static TestBase()
  28. {
  29. #if AVALONIA_CAIRO
  30. CairoPlatform.Initialize();
  31. #elif AVALONIA_SKIA
  32. SkiaPlatform.Initialize();
  33. #else
  34. Direct2D1Platform.Initialize();
  35. #endif
  36. }
  37. public TestBase(string outputPath)
  38. {
  39. #if AVALONIA_CAIRO
  40. string testFiles = Path.GetFullPath(@"..\..\tests\TestFiles\Cairo");
  41. #elif AVALONIA_SKIA
  42. string testFiles = Path.GetFullPath(@"..\..\tests\TestFiles\Skia");
  43. #else
  44. string testFiles = Path.GetFullPath(@"..\..\tests\TestFiles\Direct2D1");
  45. #endif
  46. OutputPath = Path.Combine(testFiles, outputPath);
  47. }
  48. public string OutputPath
  49. {
  50. get;
  51. }
  52. protected void RenderToFile(Control target, [CallerMemberName] string testName = "")
  53. {
  54. if (!Directory.Exists(OutputPath))
  55. {
  56. Directory.CreateDirectory(OutputPath);
  57. }
  58. string path = Path.Combine(OutputPath, testName + ".out.png");
  59. using (RenderTargetBitmap bitmap = new RenderTargetBitmap(
  60. (int)target.Width,
  61. (int)target.Height))
  62. {
  63. Size size = new Size(target.Width, target.Height);
  64. target.Measure(size);
  65. target.Arrange(new Rect(size));
  66. bitmap.Render(target);
  67. bitmap.Save(path);
  68. }
  69. }
  70. protected void CompareImages([CallerMemberName] string testName = "")
  71. {
  72. string expectedPath = Path.Combine(OutputPath, testName + ".expected.png");
  73. string actualPath = Path.Combine(OutputPath, testName + ".out.png");
  74. MagickImage expected = new MagickImage(expectedPath);
  75. MagickImage actual = new MagickImage(actualPath);
  76. double error = expected.Compare(actual, ErrorMetric.RootMeanSquared);
  77. if (error > 0.022)
  78. {
  79. Assert.True(false, actualPath + ": Error = " + error);
  80. }
  81. }
  82. }
  83. }