TestHelpers.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Xunit.Abstractions;
  7. using Xunit;
  8. using Terminal.Gui;
  9. using Rune = System.Rune;
  10. using Attribute = Terminal.Gui.Attribute;
  11. using System.Text.RegularExpressions;
  12. using System.Reflection;
  13. // This class enables test functions annotated with the [AutoInitShutdown] attribute to
  14. // automatically call Application.Init before called and Application.Shutdown after
  15. //
  16. // This is necessary because a) Application is a singleton and Init/Shutdown must be called
  17. // as a pair, and b) all unit test functions should be atomic.
  18. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  19. public class AutoInitShutdownAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  20. static bool _init = false;
  21. public override void Before (MethodInfo methodUnderTest)
  22. {
  23. if (_init) {
  24. throw new InvalidOperationException ("After did not run.");
  25. }
  26. Application.Init (new FakeDriver (), new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  27. _init = true;
  28. }
  29. public override void After (MethodInfo methodUnderTest)
  30. {
  31. Application.Shutdown ();
  32. _init = false;
  33. }
  34. }
  35. class TestHelpers {
  36. #pragma warning disable xUnit1013 // Public method should be marked as test
  37. public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output)
  38. {
  39. #pragma warning restore xUnit1013 // Public method should be marked as test
  40. var sb = new StringBuilder ();
  41. var driver = ((FakeDriver)Application.Driver);
  42. var contents = driver.Contents;
  43. for (int r = 0; r < driver.Rows; r++) {
  44. for (int c = 0; c < driver.Cols; c++) {
  45. Rune rune = contents [r, c, 0];
  46. if (Rune.DecodeSurrogatePair (rune, out char [] spair)) {
  47. sb.Append (spair);
  48. } else {
  49. sb.Append ((char)rune);
  50. }
  51. if (Rune.ColumnWidth (rune) > 1) {
  52. c++;
  53. }
  54. }
  55. sb.AppendLine ();
  56. }
  57. var actualLook = sb.ToString ();
  58. if (!string.Equals (expectedLook, actualLook)) {
  59. // ignore trailing whitespace on each line
  60. var trailingWhitespace = new Regex (@"\s+$", RegexOptions.Multiline);
  61. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  62. expectedLook = trailingWhitespace.Replace (expectedLook, "").Trim ();
  63. actualLook = trailingWhitespace.Replace (actualLook, "").Trim ();
  64. // standardize line endings for the comparison
  65. expectedLook = expectedLook.Replace ("\r\n", "\n");
  66. actualLook = actualLook.Replace ("\r\n", "\n");
  67. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  68. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  69. Assert.Equal (expectedLook, actualLook);
  70. }
  71. }
  72. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
  73. {
  74. var lines = new List<List<Rune>> ();
  75. var sb = new StringBuilder ();
  76. var driver = ((FakeDriver)Application.Driver);
  77. var x = -1;
  78. var y = -1;
  79. int w = -1;
  80. int h = -1;
  81. var contents = driver.Contents;
  82. for (int r = 0; r < driver.Rows; r++) {
  83. var runes = new List<Rune> ();
  84. for (int c = 0; c < driver.Cols; c++) {
  85. var rune = (Rune)contents [r, c, 0];
  86. if (rune != ' ') {
  87. if (x == -1) {
  88. x = c;
  89. y = r;
  90. for (int i = 0; i < c; i++) {
  91. runes.InsertRange (i, new List<Rune> () { ' ' });
  92. }
  93. }
  94. if (Rune.ColumnWidth (rune) > 1) {
  95. c++;
  96. }
  97. if (c + 1 > w) {
  98. w = c + 1;
  99. }
  100. h = r - y + 1;
  101. }
  102. if (x > -1) {
  103. runes.Add (rune);
  104. }
  105. }
  106. if (runes.Count > 0) {
  107. lines.Add (runes);
  108. }
  109. }
  110. // Remove unnecessary empty lines
  111. if (lines.Count > 0) {
  112. for (int r = lines.Count - 1; r > h - 1; r--) {
  113. lines.RemoveAt (r);
  114. }
  115. }
  116. // Remove trailing whitespace on each line
  117. for (int r = 0; r < lines.Count; r++) {
  118. List<Rune> row = lines [r];
  119. for (int c = row.Count - 1; c >= 0; c--) {
  120. var rune = row [c];
  121. if (rune != ' ' || (row.Sum (x => Rune.ColumnWidth (x)) == w)) {
  122. break;
  123. }
  124. row.RemoveAt (c);
  125. }
  126. }
  127. // Convert Rune list to string
  128. for (int r = 0; r < lines.Count; r++) {
  129. var line = NStack.ustring.Make (lines [r]).ToString ();
  130. if (r == lines.Count - 1) {
  131. sb.Append (line);
  132. } else {
  133. sb.AppendLine (line);
  134. }
  135. }
  136. var actualLook = sb.ToString ();
  137. if (!string.Equals (expectedLook, actualLook)) {
  138. // standardize line endings for the comparison
  139. expectedLook = expectedLook.Replace ("\r\n", "\n");
  140. actualLook = actualLook.Replace ("\r\n", "\n");
  141. // Remove the first and the last line ending from the expectedLook
  142. if (expectedLook.StartsWith ("\n")) {
  143. expectedLook = expectedLook [1..];
  144. }
  145. if (expectedLook.EndsWith ("\n")) {
  146. expectedLook = expectedLook [..^1];
  147. }
  148. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  149. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  150. Assert.Equal (expectedLook, actualLook);
  151. }
  152. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  153. }
  154. #pragma warning disable xUnit1013 // Public method should be marked as test
  155. /// <summary>
  156. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  157. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  158. /// test method will verify those colors were used in the row/col of the console during rendering
  159. /// </summary>
  160. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  161. /// <param name="expectedColors"></param>
  162. public static void AssertDriverColorsAre (string expectedLook, Attribute [] expectedColors)
  163. {
  164. #pragma warning restore xUnit1013 // Public method should be marked as test
  165. if (expectedColors.Length > 10) {
  166. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  167. }
  168. expectedLook = expectedLook.Trim ();
  169. var driver = ((FakeDriver)Application.Driver);
  170. var contents = driver.Contents;
  171. int r = 0;
  172. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  173. for (int c = 0; c < line.Length; c++) {
  174. int val = contents [r, c, 1];
  175. var match = expectedColors.Where (e => e.Value == val).ToList ();
  176. if (match.Count == 0) {
  177. throw new Exception ($"Unexpected color {DescribeColor (val)} was used at row {r} and col {c} (indexes start at 0). Color value was {val} (expected colors were {string.Join (",", expectedColors.Select (c => c.Value))})");
  178. } else if (match.Count > 1) {
  179. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  180. }
  181. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  182. var userExpected = line [c];
  183. if (colorUsed != userExpected) {
  184. throw new Exception ($"Colors used did not match expected at row {r} and col {c} (indexes start at 0). Color index used was {DescribeColor (colorUsed)} but test expected {DescribeColor (userExpected)} (these are indexes into the expectedColors array)");
  185. }
  186. }
  187. r++;
  188. }
  189. }
  190. private static object DescribeColor (int userExpected)
  191. {
  192. var a = new Attribute (userExpected);
  193. return $"{a.Foreground},{a.Background}";
  194. }
  195. }