LayoutTest.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using System.Runtime.CompilerServices;
  2. using System.Text;
  3. using NUnit.Framework.Constraints;
  4. using QuestPDF.Drawing.Exceptions;
  5. using QuestPDF.Elements;
  6. using QuestPDF.Helpers;
  7. namespace QuestPDF.LayoutTests.TestEngine;
  8. internal class LayoutTest
  9. {
  10. private string TestIdentifier { get; set; }
  11. private Size AvailableSpace { get; set; }
  12. private DrawingRecorder ActualDrawingRecorder { get; } = new();
  13. private DrawingRecorder ExpectedDrawingRecorder { get; } = new();
  14. private IContainer? Content { get; set; }
  15. private static readonly NUnitEqualityComparer Comparer = new();
  16. public static LayoutTest HavingSpaceOfSize(float width, float height, [CallerMemberName] string testIdentifier = "test")
  17. {
  18. var layoutTest = new LayoutTest
  19. {
  20. TestIdentifier = testIdentifier,
  21. AvailableSpace = new Size(width, height)
  22. };
  23. return layoutTest;
  24. }
  25. public LayoutTest ForContent(Action<IContainer> handler)
  26. {
  27. if (Content != null)
  28. throw new InvalidOperationException("Content has already been defined.");
  29. Content = new Container();
  30. Content
  31. .Width(AvailableSpace.Width)
  32. .Height(AvailableSpace.Height)
  33. .ElementObserverSetter(ActualDrawingRecorder)
  34. .Mock("$document")
  35. .Element(handler);
  36. return this;
  37. }
  38. public void ExpectDrawResult(Action<ExpectedDocumentLayoutDescriptor> handler)
  39. {
  40. if (!ActualDrawingRecorder.GetDrawingEvents().Any())
  41. PerformTest();
  42. var builder = new ExpectedDocumentLayoutDescriptor(ExpectedDrawingRecorder);
  43. handler(builder);
  44. var actualDrawingEvents = ActualDrawingRecorder.GetDrawingEvents();
  45. var expectedDrawingEvents = ExpectedDrawingRecorder.GetDrawingEvents();
  46. if (CheckIfIdentical(actualDrawingEvents, expectedDrawingEvents))
  47. {
  48. Assert.Pass();
  49. }
  50. else
  51. {
  52. DrawLog(actualDrawingEvents, expectedDrawingEvents);
  53. Assert.Fail($"The drawing operations do not match the expected result. See the log above for details. Test identifier: '{TestIdentifier}'.");
  54. }
  55. static bool CheckIfIdentical(IReadOnlyCollection<ElementDrawingEvent> actual, IReadOnlyCollection<ElementDrawingEvent> expected)
  56. {
  57. if (actual.Count != expected.Count)
  58. return false;
  59. return actual.Zip(expected, Compare).All(x => x);
  60. }
  61. static bool Compare(ElementDrawingEvent? actual, ElementDrawingEvent? expected)
  62. {
  63. if (actual == null && expected == null)
  64. return true;
  65. if (actual == null || expected == null)
  66. return false;
  67. var tolerance = Tolerance.Default;
  68. return actual.ObserverId == expected.ObserverId &&
  69. actual.PageNumber == expected.PageNumber &&
  70. Position.Equal(actual.Position, expected.Position) &&
  71. Size.Equal(actual.Size, expected.Size) &&
  72. (expected.StateAfterDrawing == null || Comparer.AreEqual(actual.StateAfterDrawing, expected.StateAfterDrawing, ref tolerance));
  73. }
  74. static void DrawLog(IReadOnlyCollection<ElementDrawingEvent> actualEvents, IReadOnlyCollection<ElementDrawingEvent> expectedEvents)
  75. {
  76. var identicalLines = actualEvents.Zip(expectedEvents, Compare).TakeWhile(x => x).Count();
  77. if (identicalLines > 0)
  78. {
  79. TestContext.Out.WriteLine("IDENTICAL");
  80. TestContext.Out.WriteLine(DrawHeader());
  81. foreach (var actualEvent in actualEvents.Take(identicalLines))
  82. TestContext.Out.WriteLine($"🟩\t{GetEventAsText(actualEvent)}");
  83. }
  84. if (expectedEvents.Count > identicalLines)
  85. {
  86. TestContext.Out.WriteLine();
  87. TestContext.Out.WriteLine("EXPECTED");
  88. TestContext.Out.WriteLine(DrawHeader());
  89. foreach (var expectedEvent in expectedEvents.Skip(identicalLines))
  90. TestContext.Out.WriteLine($"🟧\t{GetEventAsText(expectedEvent)}");
  91. }
  92. if (actualEvents.Count > identicalLines)
  93. {
  94. TestContext.Out.WriteLine();
  95. TestContext.Out.WriteLine("ACTUAL");
  96. TestContext.Out.WriteLine(DrawHeader());
  97. foreach (var actualEvent in actualEvents.Skip(identicalLines))
  98. TestContext.Out.WriteLine($"🟥\t{GetEventAsText(actualEvent)}");
  99. }
  100. }
  101. static string DrawHeader()
  102. {
  103. var mock = "Mock".PadRight(12);
  104. var page = "Page".PadRight(6);
  105. var x = "X".PadRight(8);
  106. var y = "Y".PadRight(8);
  107. var width = "W".PadRight(10);
  108. var height = "H";
  109. return $"\t{mock} {page} {x} {y} {width} {height}";
  110. }
  111. static string GetEventAsText(ElementDrawingEvent drawingEvent)
  112. {
  113. var observerId = drawingEvent.ObserverId.PadRight(12);
  114. var pageNumber = $"{drawingEvent.PageNumber}".PadRight(6);
  115. var positionX = $"{drawingEvent.Position.X}".PadRight(8);
  116. var positionY = $"{drawingEvent.Position.Y}".PadRight(8);
  117. var sizeWidth = $"{drawingEvent.Size.Width}".PadRight(10);
  118. var sizeHeight = $"{drawingEvent.Size.Height}";
  119. return $"{observerId} {pageNumber} {positionX} {positionY} {sizeWidth} {sizeHeight}";
  120. }
  121. }
  122. public void ExpectLayoutException(string reason)
  123. {
  124. try
  125. {
  126. QuestPDF.Settings.EnableDebugging = true;
  127. PerformTest();
  128. }
  129. catch (DocumentLayoutException e)
  130. {
  131. Assert.That(e.Message.Contains(reason));
  132. Assert.Pass($"The expected exception was thrown: {e.Message}");
  133. }
  134. catch
  135. {
  136. Assert.Fail("Un expected exception was thrown.");
  137. }
  138. }
  139. private void PerformTest()
  140. {
  141. Document
  142. .Create(document =>
  143. {
  144. document.Page(page =>
  145. {
  146. page.MinSize(new PageSize(0, 0));
  147. page.MaxSize(new PageSize(Size.Infinity, Size.Infinity));
  148. page.Content().Element(Content);
  149. });
  150. })
  151. .Generate(new LayoutTestDocumentCanvas());
  152. }
  153. public LayoutTest VisualizeOutput()
  154. {
  155. if (Content == null)
  156. throw new InvalidOperationException("Content has not been defined.");
  157. Document
  158. .Create(document =>
  159. {
  160. document.Page(page =>
  161. {
  162. page.MinSize(new PageSize(0, 0));
  163. page.MaxSize(new PageSize(Size.Infinity, Size.Infinity));
  164. page.Content().Element(Content);
  165. });
  166. })
  167. .GeneratePdfAndShow();
  168. return this;
  169. }
  170. }