LayoutTest.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Diagnostics;
  2. using System.Runtime.CompilerServices;
  3. using QuestPDF.Elements;
  4. using QuestPDF.Fluent;
  5. using QuestPDF.Infrastructure;
  6. namespace QuestPDF.LayoutTests.TestEngine;
  7. internal sealed class LayoutTest
  8. {
  9. private string TestIdentifier { get; set; }
  10. private LayoutTestResult TestResult { get; } = new LayoutTestResult();
  11. public static LayoutTest HavingSpaceOfSize(float width, float height, [CallerMemberName] string testIdentifier = "test")
  12. {
  13. var layoutTest = new LayoutTest
  14. {
  15. TestIdentifier = testIdentifier,
  16. TestResult =
  17. {
  18. PageSize = new Size(width, height)
  19. }
  20. };
  21. return layoutTest;
  22. }
  23. public LayoutTest WithContent(Action<IContainer> handler)
  24. {
  25. var container = new Container();
  26. container.Element(handler);
  27. TestResult.ActualLayout = LayoutTestExecutor.Execute(TestResult.PageSize, container);
  28. return this;
  29. }
  30. public void ExpectedDrawResult(Action<ExpectedDocumentLayoutDescriptor> handler)
  31. {
  32. var builder = new ExpectedDocumentLayoutDescriptor();
  33. handler(builder);
  34. TestResult.ExpectedLayout = builder.DocumentLayout;
  35. GenerateTestPreview();
  36. LayoutTestValidator.Validate(TestResult);
  37. }
  38. private void GenerateTestPreview()
  39. {
  40. if (!Debugger.IsAttached)
  41. {
  42. Console.WriteLine("Debugger is not attached. Skipping test preview generation");
  43. return;
  44. }
  45. var path = Path.Combine(Path.GetTempPath(), $"{TestIdentifier}.pdf");
  46. if (File.Exists(path))
  47. File.Delete(path);
  48. var stream = new FileStream(path, FileMode.CreateNew);
  49. LayoutTestResultVisualization.Visualize(TestResult, stream);
  50. stream.Dispose();
  51. Console.WriteLine($"Generated test case preview: {path}");
  52. }
  53. }