TestHelpers.cs 15 KB

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