TestHelpers.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. using System.IO;
  15. namespace Terminal.Gui;
  16. // This class enables test functions annotated with the [AutoInitShutdown] attribute to
  17. // automatically call Application.Init at start of the test and Application.Shutdown after the
  18. // test exits.
  19. //
  20. // This is necessary because a) Application is a singleton and Init/Shutdown must be called
  21. // as a pair, and b) all unit test functions should be atomic..
  22. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  23. public class AutoInitShutdownAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  24. /// <summary>
  25. /// Initializes a [AutoInitShutdown] attribute, which determines if/how Application.Init and
  26. /// Application.Shutdown are automatically called Before/After a test runs.
  27. /// </summary>
  28. /// <param name="autoInit">If true, Application.Init will be called Before the test runs.</param>
  29. /// <param name="autoShutdown">If true, Application.Shutdown will be called After the test runs.</param>
  30. /// <param name="consoleDriverType">Determines which ConsoleDriver (FakeDriver, WindowsDriver,
  31. /// CursesDriver, NetDriver) will be used when Application.Init is called. If null FakeDriver will be used.
  32. /// Only valid if <paramref name="autoInit"/> is true.</param>
  33. /// <param name="useFakeClipboard">If true, will force the use of <see cref="FakeDriver.FakeClipboard"/>.
  34. /// Only valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  35. /// <param name="fakeClipboardAlwaysThrowsNotSupportedException">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="fakeClipboardIsSupportedAlwaysTrue">Only valid if <paramref name="autoInit"/> is true.
  38. /// Only valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  39. /// <param name="configLocation">Determines what config file locations <see cref="ConfigurationManager"/> will
  40. /// load from.</param>
  41. public AutoInitShutdownAttribute (bool autoInit = true,
  42. Type consoleDriverType = null,
  43. bool useFakeClipboard = true,
  44. bool fakeClipboardAlwaysThrowsNotSupportedException = false,
  45. bool fakeClipboardIsSupportedAlwaysTrue = false,
  46. ConfigurationManager.ConfigLocations configLocation = ConfigurationManager.ConfigLocations.DefaultOnly)
  47. {
  48. AutoInit = autoInit;
  49. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  50. _driverType = consoleDriverType ?? typeof (FakeDriver);
  51. FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
  52. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
  53. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  54. ConfigurationManager.Locations = configLocation;
  55. }
  56. bool AutoInit { get; }
  57. Type _driverType;
  58. public override void Before (MethodInfo methodUnderTest)
  59. {
  60. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  61. if (AutoInit) {
  62. #if DEBUG_IDISPOSABLE
  63. // Clear out any lingering Responder instances from previous tests
  64. if (Responder.Instances.Count == 0) {
  65. Assert.Empty (Responder.Instances);
  66. } else {
  67. Responder.Instances.Clear ();
  68. }
  69. #endif
  70. Application.Init ((ConsoleDriver)Activator.CreateInstance (_driverType));
  71. }
  72. }
  73. public override void After (MethodInfo methodUnderTest)
  74. {
  75. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  76. if (AutoInit) {
  77. Application.Shutdown ();
  78. #if DEBUG_IDISPOSABLE
  79. if (Responder.Instances.Count == 0) {
  80. Assert.Empty (Responder.Instances);
  81. } else {
  82. Responder.Instances.Clear ();
  83. }
  84. #endif
  85. }
  86. }
  87. }
  88. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  89. public class TestRespondersDisposed : Xunit.Sdk.BeforeAfterTestAttribute {
  90. public TestRespondersDisposed ()
  91. {
  92. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  93. }
  94. public override void Before (MethodInfo methodUnderTest)
  95. {
  96. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  97. #if DEBUG_IDISPOSABLE
  98. // Clear out any lingering Responder instances from previous tests
  99. Responder.Instances.Clear ();
  100. Assert.Empty (Responder.Instances);
  101. #endif
  102. }
  103. public override void After (MethodInfo methodUnderTest)
  104. {
  105. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  106. #if DEBUG_IDISPOSABLE
  107. Assert.Empty (Responder.Instances);
  108. #endif
  109. }
  110. }
  111. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  112. public class SetupFakeDriverAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  113. /// <summary>
  114. /// Enables test functions annotated with the [SetupFakeDriver] attribute to
  115. /// set Application.Driver to new FakeDriver().
  116. /// </summary>
  117. public SetupFakeDriverAttribute ()
  118. {
  119. }
  120. public override void Before (MethodInfo methodUnderTest)
  121. {
  122. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  123. Assert.Null (Application.Driver);
  124. Application.Driver = new FakeDriver ();
  125. }
  126. public override void After (MethodInfo methodUnderTest)
  127. {
  128. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  129. Application.Driver = null;
  130. }
  131. }
  132. partial class TestHelpers {
  133. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  134. private static partial Regex TrailingWhiteSpaceRegEx ();
  135. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  136. private static partial Regex LeadingWhitespaceRegEx ();
  137. #pragma warning disable xUnit1013 // Public method should be marked as test
  138. /// <summary>
  139. /// Asserts that the driver contents match the expected contents, optionally ignoring any trailing whitespace.
  140. /// </summary>
  141. /// <param name="expectedLook"></param>
  142. /// <param name="output"></param>
  143. /// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  144. /// <param name="ignoreLeadingWhitespace"></param>
  145. public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output, ConsoleDriver driver = null, bool ignoreLeadingWhitespace = false)
  146. {
  147. #pragma warning restore xUnit1013 // Public method should be marked as test
  148. var sb = new StringBuilder ();
  149. driver ??= Application.Driver;
  150. var contents = driver.Contents;
  151. for (int r = 0; r < driver.Rows; r++) {
  152. for (int c = 0; c < driver.Cols; c++) {
  153. Rune rune = contents [r, c].Rune;
  154. if (rune.DecodeSurrogatePair (out char [] spair)) {
  155. sb.Append (spair);
  156. } else {
  157. sb.Append ((char)rune.Value);
  158. }
  159. if (rune.GetColumns () > 1) {
  160. c++;
  161. }
  162. // See Issue #2616
  163. //foreach (var combMark in contents [r, c].CombiningMarks) {
  164. // sb.Append ((char)combMark.Value);
  165. //}
  166. }
  167. sb.AppendLine ();
  168. }
  169. var actualLook = sb.ToString ();
  170. if (string.Equals (expectedLook, actualLook)) return;
  171. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  172. expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
  173. actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
  174. if (ignoreLeadingWhitespace) {
  175. expectedLook = LeadingWhitespaceRegEx ().Replace (expectedLook, "").Trim ();
  176. actualLook = LeadingWhitespaceRegEx ().Replace (actualLook, "").Trim ();
  177. }
  178. // standardize line endings for the comparison
  179. expectedLook = expectedLook.Replace ("\r\n", "\n");
  180. actualLook = actualLook.Replace ("\r\n", "\n");
  181. // If test is about to fail show user what things looked like
  182. if (!string.Equals (expectedLook, actualLook)) {
  183. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  184. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  185. }
  186. Assert.Equal (expectedLook, actualLook);
  187. }
  188. /// <summary>
  189. /// Asserts that the driver contents are equal to the expected look, and that the cursor is at the expected position.
  190. /// </summary>
  191. /// <param name="expectedLook"></param>
  192. /// <param name="output"></param>
  193. /// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  194. /// <returns></returns>
  195. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output, ConsoleDriver driver = null)
  196. {
  197. var lines = new List<List<Rune>> ();
  198. var sb = new StringBuilder ();
  199. driver ??= Application.Driver;
  200. var x = -1;
  201. var y = -1;
  202. var w = -1;
  203. var h = -1;
  204. var contents = driver.Contents;
  205. for (var r = 0; r < driver.Rows; r++) {
  206. var runes = new List<Rune> ();
  207. for (var c = 0; c < driver.Cols; c++) {
  208. Rune rune = contents [r, c].Rune;
  209. if (rune != (Rune)' ') {
  210. if (x == -1) {
  211. x = c;
  212. y = r;
  213. for (int i = 0; i < c; i++) {
  214. runes.InsertRange (i, new List<Rune> () { (Rune)' ' });
  215. }
  216. }
  217. if (rune.GetColumns () > 1) {
  218. c++;
  219. }
  220. if (c + 1 > w) {
  221. w = c + 1;
  222. }
  223. h = r - y + 1;
  224. }
  225. if (x > -1) runes.Add (rune);
  226. // See Issue #2616
  227. //foreach (var combMark in contents [r, c].CombiningMarks) {
  228. // runes.Add (combMark);
  229. //}
  230. }
  231. if (runes.Count > 0) lines.Add (runes);
  232. }
  233. // Remove unnecessary empty lines
  234. if (lines.Count > 0) {
  235. for (var r = lines.Count - 1; r > h - 1; r--) lines.RemoveAt (r);
  236. }
  237. // Remove trailing whitespace on each line
  238. foreach (var row in lines) {
  239. for (var c = row.Count - 1; c >= 0; c--) {
  240. var rune = row [c];
  241. if (rune != (Rune)' ' || (row.Sum (x => x.GetColumns ()) == w)) {
  242. break;
  243. }
  244. row.RemoveAt (c);
  245. }
  246. }
  247. // Convert Rune list to string
  248. for (int r = 0; r < lines.Count; r++) {
  249. var line = Terminal.Gui.StringExtensions.ToString (lines [r]).ToString ();
  250. if (r == lines.Count - 1) {
  251. sb.Append (line);
  252. } else {
  253. sb.AppendLine (line);
  254. }
  255. }
  256. var actualLook = sb.ToString ();
  257. if (string.Equals (expectedLook, actualLook)) {
  258. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  259. }
  260. // standardize line endings for the comparison
  261. expectedLook = expectedLook.Replace ("\r\n", "\n");
  262. actualLook = actualLook.Replace ("\r\n", "\n");
  263. // Remove the first and the last line ending from the expectedLook
  264. if (expectedLook.StartsWith ("\n")) expectedLook = expectedLook [1..];
  265. if (expectedLook.EndsWith ("\n")) expectedLook = expectedLook [..^1];
  266. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  267. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  268. Assert.Equal (expectedLook, actualLook);
  269. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  270. }
  271. #pragma warning disable xUnit1013 // Public method should be marked as test
  272. /// <summary>
  273. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  274. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  275. /// test method will verify those colors were used in the row/col of the console during rendering
  276. /// </summary>
  277. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  278. /// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  279. /// <param name="expectedColors"></param>
  280. public static void AssertDriverColorsAre (string expectedLook, ConsoleDriver driver = null, params Attribute [] expectedColors)
  281. {
  282. #pragma warning restore xUnit1013 // Public method should be marked as test
  283. if (expectedColors.Length > 10) throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  284. expectedLook = expectedLook.Trim ();
  285. driver ??= Application.Driver;
  286. var contents = driver.Contents;
  287. var r = 0;
  288. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  289. for (var c = 0; c < line.Length; c++) {
  290. var val = contents [r, c].Attribute;
  291. var match = expectedColors.Where (e => e == val).ToList ();
  292. switch (match.Count) {
  293. case 0:
  294. 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 ()))})");
  295. case > 1:
  296. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  297. }
  298. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  299. var userExpected = line [c];
  300. 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)");
  301. }
  302. r++;
  303. }
  304. }
  305. /// <summary>
  306. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering.
  307. /// If one or more of the expected colors are not used then the failure will output both
  308. /// the colors that were found to be used and which of your expectations was not met.
  309. /// </summary>
  310. /// <param name="driver">if null uses <see cref="Application.Driver"/></param>
  311. /// <param name="expectedColors"></param>
  312. internal static void AssertDriverUsedColors (ConsoleDriver driver = null, params Attribute [] expectedColors)
  313. {
  314. driver ??= Application.Driver;
  315. var contents = driver.Contents;
  316. var toFind = expectedColors.ToList ();
  317. // Contents 3rd column is an Attribute
  318. var colorsUsed = new HashSet<Attribute> ();
  319. for (var r = 0; r < driver.Rows; r++) {
  320. for (var c = 0; c < driver.Cols; c++) {
  321. var val = contents [r, c].Attribute;
  322. if (val.HasValue) {
  323. colorsUsed.Add (val.Value);
  324. var match = toFind.FirstOrDefault (e => e == val);
  325. // need to check twice because Attribute is a struct and therefore cannot be null
  326. if (toFind.Any (e => e == val)) {
  327. toFind.Remove (match);
  328. }
  329. }
  330. }
  331. }
  332. if (!toFind.Any ()) {
  333. return;
  334. }
  335. var sb = new StringBuilder ();
  336. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
  337. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
  338. throw new Exception (sb.ToString ());
  339. }
  340. #pragma warning disable xUnit1013 // Public method should be marked as test
  341. /// <summary>
  342. /// Verifies two strings are equivalent. If the assert fails, output will be generated to standard
  343. /// output showing the expected and actual look.
  344. /// </summary>
  345. /// <param name="output"></param>
  346. /// <param name="expectedLook">A string containing the expected look. Newlines should be specified as "\r\n" as
  347. /// they will be converted to <see cref="Environment.NewLine"/> to make tests platform independent.</param>
  348. /// <param name="actualLook"></param>
  349. public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
  350. {
  351. // Convert newlines to platform-specific newlines
  352. expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
  353. // If test is about to fail show user what things looked like
  354. if (!string.Equals (expectedLook, actualLook)) {
  355. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  356. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  357. }
  358. Assert.Equal (expectedLook, actualLook);
  359. }
  360. #pragma warning restore xUnit1013 // Public method should be marked as test
  361. private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
  362. {
  363. var replaced = toReplace;
  364. replaced = Environment.NewLine.Length switch {
  365. 2 when !replaced.Contains ("\r\n") => replaced.Replace ("\n", Environment.NewLine),
  366. 1 => replaced.Replace ("\r\n", Environment.NewLine),
  367. var _ => replaced
  368. };
  369. return replaced;
  370. }
  371. /// <summary>
  372. /// Gets a list of instances of all classes derived from View.
  373. /// </summary>
  374. /// <returns>List of View objects</returns>
  375. public static List<View> GetAllViews ()
  376. {
  377. return typeof (View).Assembly.GetTypes ()
  378. .Where (type => type.IsClass && !type.IsAbstract && type.IsPublic && type.IsSubclassOf (typeof (View)))
  379. .Select (type => GetTypeInitializer (type, type.GetConstructor (Array.Empty<Type> ()))).ToList ();
  380. }
  381. private static View GetTypeInitializer (Type type, ConstructorInfo ctor)
  382. {
  383. View viewType = null;
  384. if (type.IsGenericType && type.IsTypeDefinition) {
  385. List<Type> gTypes = new List<Type> ();
  386. foreach (var args in type.GetGenericArguments ()) {
  387. gTypes.Add (typeof (object));
  388. }
  389. type = type.MakeGenericType (gTypes.ToArray ());
  390. Assert.IsType (type, (View)Activator.CreateInstance (type));
  391. } else {
  392. ParameterInfo [] paramsInfo = ctor.GetParameters ();
  393. Type paramType;
  394. List<object> pTypes = new List<object> ();
  395. if (type.IsGenericType) {
  396. foreach (var args in type.GetGenericArguments ()) {
  397. paramType = args.GetType ();
  398. if (args.Name == "T") {
  399. pTypes.Add (typeof (object));
  400. } else {
  401. AddArguments (paramType, pTypes);
  402. }
  403. }
  404. }
  405. foreach (var p in paramsInfo) {
  406. paramType = p.ParameterType;
  407. if (p.HasDefaultValue) {
  408. pTypes.Add (p.DefaultValue);
  409. } else {
  410. AddArguments (paramType, pTypes);
  411. }
  412. }
  413. if (type.IsGenericType && !type.IsTypeDefinition) {
  414. viewType = (View)Activator.CreateInstance (type);
  415. Assert.IsType (type, viewType);
  416. } else {
  417. viewType = (View)ctor.Invoke (pTypes.ToArray ());
  418. Assert.IsType (type, viewType);
  419. }
  420. }
  421. return viewType;
  422. }
  423. private static void AddArguments (Type paramType, List<object> pTypes)
  424. {
  425. if (paramType == typeof (Rect)) {
  426. pTypes.Add (Rect.Empty);
  427. } else if (paramType == typeof (string)) {
  428. pTypes.Add (string.Empty);
  429. } else if (paramType == typeof (int)) {
  430. pTypes.Add (0);
  431. } else if (paramType == typeof (bool)) {
  432. pTypes.Add (true);
  433. } else if (paramType.Name == "IList") {
  434. pTypes.Add (new List<object> ());
  435. } else if (paramType.Name == "View") {
  436. var top = new Toplevel ();
  437. var view = new View ();
  438. top.Add (view);
  439. pTypes.Add (view);
  440. } else if (paramType.Name == "View[]") {
  441. pTypes.Add (new View [] { });
  442. } else if (paramType.Name == "Stream") {
  443. pTypes.Add (new MemoryStream ());
  444. } else if (paramType.Name == "String") {
  445. pTypes.Add (string.Empty);
  446. } else if (paramType.Name == "TreeView`1[T]") {
  447. pTypes.Add (string.Empty);
  448. } else {
  449. pTypes.Add (null);
  450. }
  451. }
  452. }