TestHelpers.cs 7.8 KB

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