TestHelpers.cs 15 KB

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