LayoutTest.cs 7.2 KB

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