TestHelpers.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. /// <summary>
  23. /// Initializes a [AutoInitShutdown] attribute, which determines if/how Application.Init and
  24. /// Application.Shutdown are automatically called Before/After a test runs.
  25. /// </summary>
  26. /// <param name="autoInit">If true, Application.Init will be called Before the test runs.</param>
  27. /// <param name="autoShutdown">If true, Application.Shutdown will be called After the test runs.</param>
  28. /// <param name="consoleDriverType">Determins which ConsoleDriver (FakeDriver, WindowsDriver,
  29. /// CursesDriver, NetDriver) will be used when Appliation.Init is called. If null FakeDriver will be used.
  30. /// Only valid if <paramref name="autoInit"/> is true.</param>
  31. /// <param name="useFakeClipboard">If true, will force the use of <see cref="FakeDriver.FakeClipboard"/>.
  32. /// Only valid if <see cref="consoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  33. /// <param name="fakeClipboardAlwaysThrowsNotSupportedException">Only valid if <paramref name="autoInit"/> is true.
  34. /// Only valid if <see cref="consoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  35. /// <param name="fakeClipboardIsSupportedAlwaysTrue">Only valid if <paramref name="autoInit"/> is true.
  36. /// Only valid if <see cref="consoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  37. public AutoInitShutdownAttribute (bool autoInit = true, bool autoShutdown = true,
  38. Type consoleDriverType = null,
  39. bool useFakeClipboard = false,
  40. bool fakeClipboardAlwaysThrowsNotSupportedException = false,
  41. bool fakeClipboardIsSupportedAlwaysTrue = false)
  42. {
  43. //Assert.True (autoInit == false && consoleDriverType == null);
  44. AutoInit = autoInit;
  45. AutoShutdown = autoShutdown;
  46. DriverType = consoleDriverType ?? typeof (FakeDriver);
  47. FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
  48. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
  49. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  50. }
  51. static bool _init = false;
  52. bool AutoInit { get; }
  53. bool AutoShutdown { get; }
  54. Type DriverType;
  55. public override void Before (MethodInfo methodUnderTest)
  56. {
  57. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  58. if (AutoShutdown && _init) {
  59. throw new InvalidOperationException ("After did not run when AutoShutdown was specified.");
  60. }
  61. if (AutoInit) {
  62. Application.Init ((ConsoleDriver)Activator.CreateInstance (DriverType));
  63. _init = true;
  64. }
  65. }
  66. public override void After (MethodInfo methodUnderTest)
  67. {
  68. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  69. if (AutoShutdown) {
  70. Application.Shutdown ();
  71. _init = false;
  72. }
  73. }
  74. }
  75. class TestHelpers {
  76. #pragma warning disable xUnit1013 // Public method should be marked as test
  77. public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output)
  78. {
  79. #pragma warning restore xUnit1013 // Public method should be marked as test
  80. var sb = new StringBuilder ();
  81. var driver = ((FakeDriver)Application.Driver);
  82. var contents = driver.Contents;
  83. for (int r = 0; r < driver.Rows; r++) {
  84. for (int c = 0; c < driver.Cols; c++) {
  85. Rune rune = contents [r, c, 0];
  86. if (Rune.DecodeSurrogatePair (rune, out char [] spair)) {
  87. sb.Append (spair);
  88. } else {
  89. sb.Append ((char)rune);
  90. }
  91. if (Rune.ColumnWidth (rune) > 1) {
  92. c++;
  93. }
  94. }
  95. sb.AppendLine ();
  96. }
  97. var actualLook = sb.ToString ();
  98. if (!string.Equals (expectedLook, actualLook)) {
  99. // ignore trailing whitespace on each line
  100. var trailingWhitespace = new Regex (@"\s+$", RegexOptions.Multiline);
  101. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  102. expectedLook = trailingWhitespace.Replace (expectedLook, "").Trim ();
  103. actualLook = trailingWhitespace.Replace (actualLook, "").Trim ();
  104. // standardize line endings for the comparison
  105. expectedLook = expectedLook.Replace ("\r\n", "\n");
  106. actualLook = actualLook.Replace ("\r\n", "\n");
  107. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  108. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  109. Assert.Equal (expectedLook, actualLook);
  110. }
  111. }
  112. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
  113. {
  114. var lines = new List<List<Rune>> ();
  115. var sb = new StringBuilder ();
  116. var driver = ((FakeDriver)Application.Driver);
  117. var x = -1;
  118. var y = -1;
  119. int w = -1;
  120. int h = -1;
  121. var contents = driver.Contents;
  122. for (int r = 0; r < driver.Rows; r++) {
  123. var runes = new List<Rune> ();
  124. for (int c = 0; c < driver.Cols; c++) {
  125. var rune = (Rune)contents [r, c, 0];
  126. if (rune != ' ') {
  127. if (x == -1) {
  128. x = c;
  129. y = r;
  130. for (int i = 0; i < c; i++) {
  131. runes.InsertRange (i, new List<Rune> () { ' ' });
  132. }
  133. }
  134. if (Rune.ColumnWidth (rune) > 1) {
  135. c++;
  136. }
  137. if (c + 1 > w) {
  138. w = c + 1;
  139. }
  140. h = r - y + 1;
  141. }
  142. if (x > -1) {
  143. runes.Add (rune);
  144. }
  145. }
  146. if (runes.Count > 0) {
  147. lines.Add (runes);
  148. }
  149. }
  150. // Remove unnecessary empty lines
  151. if (lines.Count > 0) {
  152. for (int r = lines.Count - 1; r > h - 1; r--) {
  153. lines.RemoveAt (r);
  154. }
  155. }
  156. // Remove trailing whitespace on each line
  157. for (int r = 0; r < lines.Count; r++) {
  158. List<Rune> row = lines [r];
  159. for (int c = row.Count - 1; c >= 0; c--) {
  160. var rune = row [c];
  161. if (rune != ' ' || (row.Sum (x => Rune.ColumnWidth (x)) == w)) {
  162. break;
  163. }
  164. row.RemoveAt (c);
  165. }
  166. }
  167. // Convert Rune list to string
  168. for (int r = 0; r < lines.Count; r++) {
  169. var line = NStack.ustring.Make (lines [r]).ToString ();
  170. if (r == lines.Count - 1) {
  171. sb.Append (line);
  172. } else {
  173. sb.AppendLine (line);
  174. }
  175. }
  176. var actualLook = sb.ToString ();
  177. if (!string.Equals (expectedLook, actualLook)) {
  178. // standardize line endings for the comparison
  179. expectedLook = expectedLook.Replace ("\r\n", "\n");
  180. actualLook = actualLook.Replace ("\r\n", "\n");
  181. // Remove the first and the last line ending from the expectedLook
  182. if (expectedLook.StartsWith ("\n")) {
  183. expectedLook = expectedLook [1..];
  184. }
  185. if (expectedLook.EndsWith ("\n")) {
  186. expectedLook = expectedLook [..^1];
  187. }
  188. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  189. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  190. Assert.Equal (expectedLook, actualLook);
  191. }
  192. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  193. }
  194. #pragma warning disable xUnit1013 // Public method should be marked as test
  195. /// <summary>
  196. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  197. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  198. /// test method will verify those colors were used in the row/col of the console during rendering
  199. /// </summary>
  200. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  201. /// <param name="expectedColors"></param>
  202. public static void AssertDriverColorsAre (string expectedLook, Attribute [] expectedColors)
  203. {
  204. #pragma warning restore xUnit1013 // Public method should be marked as test
  205. if (expectedColors.Length > 10) {
  206. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  207. }
  208. expectedLook = expectedLook.Trim ();
  209. var driver = ((FakeDriver)Application.Driver);
  210. var contents = driver.Contents;
  211. int r = 0;
  212. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  213. for (int c = 0; c < line.Length; c++) {
  214. int val = contents [r, c, 1];
  215. var match = expectedColors.Where (e => e.Value == val).ToList ();
  216. if (match.Count == 0) {
  217. 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))})");
  218. } else if (match.Count > 1) {
  219. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  220. }
  221. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  222. var userExpected = line [c];
  223. if (colorUsed != userExpected) {
  224. 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)");
  225. }
  226. }
  227. r++;
  228. }
  229. }
  230. private static object DescribeColor (int userExpected)
  231. {
  232. var a = new Attribute (userExpected);
  233. return $"{a.Foreground},{a.Background}";
  234. }
  235. }