TestHelpers.cs 16 KB

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