TestHelpers.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 Attribute = Terminal.Gui.Attribute;
  12. using Microsoft.VisualStudio.TestPlatform.Utilities;
  13. using Xunit.Sdk;
  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">Determines which ConsoleDriver (FakeDriver, WindowsDriver,
  29. /// CursesDriver, NetDriver) will be used when Application.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. /// <param name="configLocation">Determines what config file locations <see cref="ConfigurationManager"/> will
  38. /// load from.</param>
  39. public AutoInitShutdownAttribute (bool autoInit = true, bool autoShutdown = true,
  40. Type consoleDriverType = null,
  41. bool useFakeClipboard = true,
  42. bool fakeClipboardAlwaysThrowsNotSupportedException = false,
  43. bool fakeClipboardIsSupportedAlwaysTrue = false,
  44. ConfigurationManager.ConfigLocations configLocation = ConfigurationManager.ConfigLocations.DefaultOnly)
  45. {
  46. //Assert.True (autoInit == false && consoleDriverType == null);
  47. AutoInit = autoInit;
  48. AutoShutdown = autoShutdown;
  49. DriverType = consoleDriverType ?? typeof (FakeDriver);
  50. FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
  51. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
  52. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  53. ConfigurationManager.Locations = configLocation;
  54. }
  55. static bool _init = false;
  56. bool AutoInit { get; }
  57. bool AutoShutdown { get; }
  58. Type DriverType;
  59. public override void Before (MethodInfo methodUnderTest)
  60. {
  61. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  62. if (AutoShutdown && _init) {
  63. throw new InvalidOperationException ("After did not run when AutoShutdown was specified.");
  64. }
  65. if (AutoInit) {
  66. Application.Init ((ConsoleDriver)Activator.CreateInstance (DriverType));
  67. _init = true;
  68. }
  69. }
  70. public override void After (MethodInfo methodUnderTest)
  71. {
  72. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  73. if (AutoShutdown) {
  74. Application.Shutdown ();
  75. _init = false;
  76. }
  77. }
  78. }
  79. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  80. public class SetupFakeDriverAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  81. /// <summary>
  82. /// Enables test functions annotated with the [SetupFakeDriver] attribute to
  83. /// set Application.Driver to new FakeDriver().
  84. /// </summary>
  85. public SetupFakeDriverAttribute ()
  86. {
  87. }
  88. public override void Before (MethodInfo methodUnderTest)
  89. {
  90. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  91. Assert.Null (Application.Driver);
  92. Application.Driver = new FakeDriver ();
  93. }
  94. public override void After (MethodInfo methodUnderTest)
  95. {
  96. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  97. Application.Driver = null;
  98. }
  99. }
  100. class TestHelpers {
  101. #pragma warning disable xUnit1013 // Public method should be marked as test
  102. public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output, bool ignoreLeadingWhitespace = false)
  103. {
  104. #pragma warning restore xUnit1013 // Public method should be marked as test
  105. var sb = new StringBuilder ();
  106. var driver = ((FakeDriver)Application.Driver);
  107. var contents = driver.Contents;
  108. for (int r = 0; r < driver.Rows; r++) {
  109. for (int c = 0; c < driver.Cols; c++) {
  110. Rune rune = (Rune)contents [r, c, 0];
  111. if (rune.DecodeSurrogatePair (out char [] spair)) {
  112. sb.Append (spair);
  113. } else {
  114. sb.Append ((char)rune.Value);
  115. }
  116. if (rune.GetColumns () > 1) {
  117. c++;
  118. }
  119. }
  120. sb.AppendLine ();
  121. }
  122. var actualLook = sb.ToString ();
  123. if (!string.Equals (expectedLook, actualLook)) {
  124. // ignore trailing whitespace on each line
  125. var trailingWhitespace = new Regex (@"\s+$", RegexOptions.Multiline);
  126. var leadingWhitespace = new Regex (@"^\s+", RegexOptions.Multiline);
  127. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  128. expectedLook = trailingWhitespace.Replace (expectedLook, "").Trim ();
  129. actualLook = trailingWhitespace.Replace (actualLook, "").Trim ();
  130. if (ignoreLeadingWhitespace) {
  131. expectedLook = leadingWhitespace.Replace (expectedLook, "").Trim ();
  132. actualLook = leadingWhitespace.Replace (actualLook, "").Trim ();
  133. }
  134. // standardize line endings for the comparison
  135. expectedLook = expectedLook.Replace ("\r\n", "\n");
  136. actualLook = actualLook.Replace ("\r\n", "\n");
  137. // If test is about to fail show user what things looked like
  138. if (!string.Equals (expectedLook, actualLook)) {
  139. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  140. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  141. }
  142. Assert.Equal (expectedLook, actualLook);
  143. }
  144. }
  145. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
  146. {
  147. var lines = new List<List<Rune>> ();
  148. var sb = new StringBuilder ();
  149. var driver = ((FakeDriver)Application.Driver);
  150. var x = -1;
  151. var y = -1;
  152. int w = -1;
  153. int h = -1;
  154. var contents = driver.Contents;
  155. for (int r = 0; r < driver.Rows; r++) {
  156. var runes = new List<Rune> ();
  157. for (int c = 0; c < driver.Cols; c++) {
  158. var rune = (Rune)contents [r, c, 0];
  159. if (rune != (Rune)' ') {
  160. if (x == -1) {
  161. x = c;
  162. y = r;
  163. for (int i = 0; i < c; i++) {
  164. runes.InsertRange (i, new List<Rune> () { (Rune)' ' });
  165. }
  166. }
  167. if (rune.GetColumns () > 1) {
  168. c++;
  169. }
  170. if (c + 1 > w) {
  171. w = c + 1;
  172. }
  173. h = r - y + 1;
  174. }
  175. if (x > -1) {
  176. runes.Add (rune);
  177. }
  178. }
  179. if (runes.Count > 0) {
  180. lines.Add (runes);
  181. }
  182. }
  183. // Remove unnecessary empty lines
  184. if (lines.Count > 0) {
  185. for (int r = lines.Count - 1; r > h - 1; r--) {
  186. lines.RemoveAt (r);
  187. }
  188. }
  189. // Remove trailing whitespace on each line
  190. for (int r = 0; r < lines.Count; r++) {
  191. List<Rune> row = lines [r];
  192. for (int c = row.Count - 1; c >= 0; c--) {
  193. var rune = row [c];
  194. if (rune != (Rune)' ' || (row.Sum (x => x.GetColumns ()) == w)) {
  195. break;
  196. }
  197. row.RemoveAt (c);
  198. }
  199. }
  200. // Convert Rune list to string
  201. for (int r = 0; r < lines.Count; r++) {
  202. var line = Terminal.Gui.StringExtensions.ToString (lines [r]).ToString ();
  203. if (r == lines.Count - 1) {
  204. sb.Append (line);
  205. } else {
  206. sb.AppendLine (line);
  207. }
  208. }
  209. var actualLook = sb.ToString ();
  210. if (!string.Equals (expectedLook, actualLook)) {
  211. // standardize line endings for the comparison
  212. expectedLook = expectedLook.Replace ("\r\n", "\n");
  213. actualLook = actualLook.Replace ("\r\n", "\n");
  214. // Remove the first and the last line ending from the expectedLook
  215. if (expectedLook.StartsWith ("\n")) {
  216. expectedLook = expectedLook [1..];
  217. }
  218. if (expectedLook.EndsWith ("\n")) {
  219. expectedLook = expectedLook [..^1];
  220. }
  221. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  222. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  223. Assert.Equal (expectedLook, actualLook);
  224. }
  225. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  226. }
  227. #pragma warning disable xUnit1013 // Public method should be marked as test
  228. /// <summary>
  229. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  230. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  231. /// test method will verify those colors were used in the row/col of the console during rendering
  232. /// </summary>
  233. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  234. /// <param name="expectedColors"></param>
  235. public static void AssertDriverColorsAre (string expectedLook, params Attribute [] expectedColors)
  236. {
  237. #pragma warning restore xUnit1013 // Public method should be marked as test
  238. if (expectedColors.Length > 10) {
  239. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  240. }
  241. expectedLook = expectedLook.Trim ();
  242. var driver = ((FakeDriver)Application.Driver);
  243. var contents = driver.Contents;
  244. int r = 0;
  245. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  246. for (int c = 0; c < line.Length; c++) {
  247. int val = contents [r, c, 1];
  248. var match = expectedColors.Where (e => e.Value == val).ToList ();
  249. if (match.Count == 0) {
  250. 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)))})");
  251. } else if (match.Count > 1) {
  252. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  253. }
  254. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  255. var userExpected = line [c];
  256. if (colorUsed != userExpected) {
  257. 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)");
  258. }
  259. }
  260. r++;
  261. }
  262. }
  263. /// <summary>
  264. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering.
  265. /// If one or more of the expected colors are not used then the failure will output both
  266. /// the colors that were found to be used and which of your expectations was not met.
  267. /// </summary>
  268. /// <param name="expectedColors"></param>
  269. internal static void AssertDriverUsedColors (params Attribute [] expectedColors)
  270. {
  271. var driver = ((FakeDriver)Application.Driver);
  272. var contents = driver.Contents;
  273. var toFind = expectedColors.ToList ();
  274. var colorsUsed = new HashSet<int> ();
  275. for (int r = 0; r < driver.Rows; r++) {
  276. for (int c = 0; c < driver.Cols; c++) {
  277. int val = contents [r, c, 1];
  278. colorsUsed.Add (val);
  279. var match = toFind.FirstOrDefault (e => e.Value == val);
  280. // need to check twice because Attribute is a struct and therefore cannot be null
  281. if (toFind.Any (e => e.Value == val)) {
  282. toFind.Remove (match);
  283. }
  284. }
  285. }
  286. if(toFind.Any()) {
  287. var sb = new StringBuilder ();
  288. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => DescribeColor (a))));
  289. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (DescribeColor)));
  290. throw new Exception (sb.ToString());
  291. }
  292. }
  293. private static object DescribeColor (int userExpected)
  294. {
  295. var a = new Attribute (userExpected);
  296. return $"{a.Foreground},{a.Background}";
  297. }
  298. #pragma warning disable xUnit1013 // Public method should be marked as test
  299. /// <summary>
  300. /// Verifies two strings are equivalent. If the assert fails, output will be generated to standard
  301. /// output showing the expected and actual look.
  302. /// </summary>
  303. /// <param name="output"></param>
  304. /// <param name="expectedLook">A string containing the expected look. Newlines should be specified as "\r\n" as
  305. /// they will be converted to <see cref="Environment.NewLine"/> to make tests platform independent.</param>
  306. /// <param name="actualLook"></param>
  307. public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
  308. {
  309. // Convert newlines to platform-specific newlines
  310. expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
  311. // If test is about to fail show user what things looked like
  312. if (!string.Equals (expectedLook, actualLook)) {
  313. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  314. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  315. }
  316. Assert.Equal (expectedLook, actualLook);
  317. }
  318. #pragma warning restore xUnit1013 // Public method should be marked as test
  319. private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
  320. {
  321. var replaced = toReplace;
  322. if (Environment.NewLine.Length == 2 && !replaced.Contains ("\r\n")) {
  323. replaced = replaced.Replace ("\n", Environment.NewLine);
  324. } else if (Environment.NewLine.Length == 1) {
  325. replaced = replaced.Replace ("\r\n", Environment.NewLine);
  326. }
  327. return replaced;
  328. }
  329. }