ExampleTestBase.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using NUnit.Framework;
  7. using QuestPDF.Drawing;
  8. using QuestPDF.Elements;
  9. using QuestPDF.Fluent;
  10. using QuestPDF.Infrastructure;
  11. using SkiaSharp;
  12. namespace QuestPDF.Examples.Engine
  13. {
  14. [TestFixture]
  15. public class ExampleTestBase
  16. {
  17. private readonly Size DefaultImageSize = new Size(400, 300);
  18. private const string ResultPath = "Result";
  19. [SetUp]
  20. public void Setup()
  21. {
  22. if (Directory.Exists(ResultPath))
  23. Directory.Delete(ResultPath, true);
  24. Directory.CreateDirectory(ResultPath);
  25. }
  26. [Test]
  27. public void RunTest()
  28. {
  29. GetType()
  30. .GetMethods()
  31. .Where(IsExampleMethod)
  32. .ToList()
  33. .ForEach(HandleExample);
  34. }
  35. private bool IsExampleMethod(MethodInfo method)
  36. {
  37. var parameters = method.GetParameters();
  38. return parameters.Length == 1 && parameters.First().ParameterType == typeof(IContainer);
  39. }
  40. private T GetAttribute<T>(MethodInfo methodInfo) where T : Attribute
  41. {
  42. return methodInfo.GetCustomAttributes().FirstOrDefault(y => y is T) as T;
  43. }
  44. private void HandleExample(MethodInfo methodInfo)
  45. {
  46. var size = GetAttribute<ImageSizeAttribute>(methodInfo)?.Size ?? DefaultImageSize;
  47. var fileName = GetAttribute<FileNameAttribute>(methodInfo)?.FileName ?? methodInfo.Name;
  48. var showResult = GetAttribute<ShowResultAttribute>(methodInfo) != null;
  49. var shouldIgnore = GetAttribute<IgnoreAttribute>(methodInfo) != null;
  50. if (shouldIgnore)
  51. return;
  52. var container = new Container();
  53. methodInfo.Invoke(this, new object[] {container});
  54. Func<int, string> fileNameSchema = i => $"{fileName.ToLower()}-${i}.png";
  55. try
  56. {
  57. var document = new SimpleDocument(container, size);
  58. document.GenerateImages(fileNameSchema);
  59. }
  60. catch (Exception e)
  61. {
  62. throw new Exception($"Cannot perform test ${fileName}", e);
  63. }
  64. if (showResult)
  65. Process.Start("explorer", fileNameSchema(0));
  66. }
  67. private byte[] RenderPage(Element element, Size size)
  68. {
  69. // scale the result so it is more readable
  70. const float scalingFactor = 2;
  71. var imageInfo = new SKImageInfo((int)(size.Width * scalingFactor), (int)(size.Height * scalingFactor));
  72. using var surface = SKSurface.Create(imageInfo);
  73. surface.Canvas.Scale(scalingFactor);
  74. var canvas = new Canvas(surface.Canvas);
  75. element?.Draw(canvas, size);
  76. surface.Canvas.Save();
  77. return surface.Snapshot().Encode(SKEncodedImageFormat.Png, 100).ToArray();
  78. }
  79. }
  80. }