TestHelpers.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. sb.Append ((char)contents [r, c, 0]);
  46. }
  47. sb.AppendLine ();
  48. }
  49. var actualLook = sb.ToString ();
  50. if (!string.Equals (expectedLook, actualLook)) {
  51. // ignore trailing whitespace on each line
  52. var trailingWhitespace = new Regex (@"\s+$", RegexOptions.Multiline);
  53. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  54. expectedLook = trailingWhitespace.Replace (expectedLook, "").Trim ();
  55. actualLook = trailingWhitespace.Replace (actualLook, "").Trim ();
  56. // standardize line endings for the comparison
  57. expectedLook = expectedLook.Replace ("\r\n", "\n");
  58. actualLook = actualLook.Replace ("\r\n", "\n");
  59. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  60. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  61. Assert.Equal (expectedLook, actualLook);
  62. }
  63. }
  64. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
  65. {
  66. var lines = new List<List<char>> ();
  67. var sb = new StringBuilder ();
  68. var driver = ((FakeDriver)Application.Driver);
  69. var x = -1;
  70. var y = -1;
  71. int w = -1;
  72. int h = -1;
  73. var contents = driver.Contents;
  74. for (int r = 0; r < driver.Rows; r++) {
  75. var runes = new List<char> ();
  76. for (int c = 0; c < driver.Cols; c++) {
  77. var rune = (char)contents [r, c, 0];
  78. if (rune != ' ') {
  79. if (x == -1) {
  80. x = c;
  81. y = r;
  82. for (int i = 0; i < c; i++) {
  83. runes.InsertRange (i, new List<char> () { ' ' });
  84. }
  85. }
  86. if (Rune.ColumnWidth (rune) > 1) {
  87. c++;
  88. }
  89. if (c + 1 > w) {
  90. w = c + 1;
  91. }
  92. h = r - y + 1;
  93. }
  94. if (x > -1) {
  95. runes.Add (rune);
  96. }
  97. }
  98. if (runes.Count > 0) {
  99. lines.Add (runes);
  100. }
  101. }
  102. // Remove unnecessary empty lines
  103. if (lines.Count > 0) {
  104. for (int r = lines.Count - 1; r > h - 1; r--) {
  105. lines.RemoveAt (r);
  106. }
  107. }
  108. // Remove trailing whitespace on each line
  109. for (int r = 0; r < lines.Count; r++) {
  110. List<char> row = lines [r];
  111. for (int c = row.Count - 1; c >= 0; c--) {
  112. var rune = row [c];
  113. if (rune != ' ' || (row.Sum (x => Rune.ColumnWidth (x)) == w)) {
  114. break;
  115. }
  116. row.RemoveAt (c);
  117. }
  118. }
  119. // Convert char list to string
  120. for (int r = 0; r < lines.Count; r++) {
  121. var line = new string (lines [r].ToArray ());
  122. if (r == lines.Count - 1) {
  123. sb.Append (line);
  124. } else {
  125. sb.AppendLine (line);
  126. }
  127. }
  128. var actualLook = sb.ToString ();
  129. if (!string.Equals (expectedLook, actualLook)) {
  130. // standardize line endings for the comparison
  131. expectedLook = expectedLook.Replace ("\r\n", "\n");
  132. actualLook = actualLook.Replace ("\r\n", "\n");
  133. // Remove the first and the last line ending from the expectedLook
  134. if (expectedLook.StartsWith ("\n")) {
  135. expectedLook = expectedLook [1..];
  136. }
  137. if (expectedLook.EndsWith ("\n")) {
  138. expectedLook = expectedLook [..^1];
  139. }
  140. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  141. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  142. Assert.Equal (expectedLook, actualLook);
  143. }
  144. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  145. }
  146. #pragma warning disable xUnit1013 // Public method should be marked as test
  147. /// <summary>
  148. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  149. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  150. /// test method will verify those colors were used in the row/col of the console during rendering
  151. /// </summary>
  152. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  153. /// <param name="expectedColors"></param>
  154. public static void AssertDriverColorsAre (string expectedLook, Attribute [] expectedColors)
  155. {
  156. #pragma warning restore xUnit1013 // Public method should be marked as test
  157. if (expectedColors.Length > 10) {
  158. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  159. }
  160. expectedLook = expectedLook.Trim ();
  161. var driver = ((FakeDriver)Application.Driver);
  162. var contents = driver.Contents;
  163. int r = 0;
  164. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  165. for (int c = 0; c < line.Length; c++) {
  166. int val = contents [r, c, 1];
  167. var match = expectedColors.Where (e => e.Value == val).ToList ();
  168. if (match.Count == 0) {
  169. 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))})");
  170. } else if (match.Count > 1) {
  171. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  172. }
  173. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  174. var userExpected = line [c];
  175. if (colorUsed != userExpected) {
  176. 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)");
  177. }
  178. }
  179. r++;
  180. }
  181. }
  182. private static object DescribeColor (int userExpected)
  183. {
  184. var a = new Attribute (userExpected);
  185. return $"{a.Foreground},{a.Background}";
  186. }
  187. }