TestHelpers.cs 10 KB

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