TestHelpers.cs 19 KB

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