LayoutTest.cs 2.0 KB

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