TestHelpers.cs 10 KB

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