LayoutTest.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. try
  36. {
  37. LayoutTestValidator.Validate(TestResult);
  38. }
  39. catch
  40. {
  41. if (Settings.LayoutTestVisualizationStrategy != LayoutTestVisualizationStrategy.Never)
  42. GenerateTestPreview();
  43. throw;
  44. }
  45. finally
  46. {
  47. if (Settings.LayoutTestVisualizationStrategy == LayoutTestVisualizationStrategy.Always)
  48. GenerateTestPreview();
  49. }
  50. }
  51. private void GenerateTestPreview()
  52. {
  53. var path = Path.Combine(Path.GetTempPath(), $"{TestIdentifier}.pdf");
  54. if (File.Exists(path))
  55. File.Delete(path);
  56. var stream = new FileStream(path, FileMode.CreateNew);
  57. LayoutTestResultVisualization.Visualize(TestResult, stream);
  58. stream.Dispose();
  59. Helpers.Helpers.OpenFileUsingDefaultProgram(path);
  60. }
  61. }