TestHelpers.cs 15 KB

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