ExampleTestBase.cs 3.0 KB

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