TestHelpers.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using Xunit.Abstractions;
  7. using Xunit.Sdk;
  8. using static Terminal.Gui.ConfigurationManager;
  9. namespace Terminal.Gui;
  10. /// <summary>
  11. /// This class enables test functions annotated with the [AutoInitShutdown] attribute to
  12. /// automatically call Application.Init at start of the test and Application.Shutdown after the
  13. /// test exits.
  14. /// This is necessary because a) Application is a singleton and Init/Shutdown must be called
  15. /// as a pair, and b) all unit test functions should be atomic..
  16. /// </summary>
  17. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
  18. public class AutoInitShutdownAttribute : BeforeAfterTestAttribute
  19. {
  20. /// <summary>
  21. /// Initializes a [AutoInitShutdown] attribute, which determines if/how Application.Init and Application.Shutdown
  22. /// are automatically called Before/After a test runs.
  23. /// </summary>
  24. /// <param name="autoInit">If true, Application.Init will be called Before the test runs.</param>
  25. /// <param name="consoleDriverType">
  26. /// Determines which IConsoleDriver (FakeDriver, WindowsDriver, CursesDriver, NetDriver)
  27. /// will be used when Application.Init is called. If null FakeDriver will be used. Only valid if
  28. /// <paramref name="autoInit"/> is true.
  29. /// </param>
  30. /// <param name="useFakeClipboard">
  31. /// If true, will force the use of <see cref="FakeDriver.FakeClipboard"/>. Only valid if
  32. /// <see cref="IConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
  33. /// </param>
  34. /// <param name="fakeClipboardAlwaysThrowsNotSupportedException">
  35. /// Only valid if <paramref name="autoInit"/> is true. Only
  36. /// valid if <see cref="IConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
  37. /// </param>
  38. /// <param name="fakeClipboardIsSupportedAlwaysTrue">
  39. /// Only valid if <paramref name="autoInit"/> is true. Only valid if
  40. /// <see cref="IConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
  41. /// </param>
  42. /// <param name="configLocation">Determines what config file locations <see cref="ConfigurationManager"/> will load from.</param>
  43. /// <param name="verifyShutdown">If true and <see cref="Application.Initialized"/> is true, the test will fail.</param>
  44. public AutoInitShutdownAttribute (
  45. bool autoInit = true,
  46. Type consoleDriverType = null,
  47. bool useFakeClipboard = true,
  48. bool fakeClipboardAlwaysThrowsNotSupportedException = false,
  49. bool fakeClipboardIsSupportedAlwaysTrue = false,
  50. ConfigLocations configLocation = ConfigLocations.Default, // DefaultOnly is the default for tests
  51. bool verifyShutdown = false
  52. )
  53. {
  54. AutoInit = autoInit;
  55. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  56. _driverType = consoleDriverType ?? typeof (FakeDriver);
  57. FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
  58. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException =
  59. fakeClipboardAlwaysThrowsNotSupportedException;
  60. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  61. Locations = configLocation;
  62. _verifyShutdown = verifyShutdown;
  63. }
  64. private readonly bool _verifyShutdown;
  65. private readonly Type _driverType;
  66. public override void After (MethodInfo methodUnderTest)
  67. {
  68. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  69. // Turn off diagnostic flags in case some test left them on
  70. View.Diagnostics = ViewDiagnosticFlags.Off;
  71. if (AutoInit)
  72. {
  73. // try
  74. {
  75. if (!_verifyShutdown)
  76. {
  77. Application.ResetState (ignoreDisposed: true);
  78. }
  79. Application.Shutdown ();
  80. #if DEBUG_IDISPOSABLE
  81. if (View.Instances.Count == 0)
  82. {
  83. Assert.Empty (View.Instances);
  84. }
  85. else
  86. {
  87. View.Instances.Clear ();
  88. }
  89. #endif
  90. }
  91. //catch (Exception e)
  92. //{
  93. // Assert.Fail ($"Application.Shutdown threw an exception after the test exited: {e}");
  94. //}
  95. //finally
  96. {
  97. #if DEBUG_IDISPOSABLE
  98. View.Instances.Clear ();
  99. Application.ResetState (true);
  100. #endif
  101. }
  102. }
  103. // Reset to defaults
  104. Locations = ConfigLocations.Default;
  105. Reset ();
  106. // Enable subsequent tests that call Init to get all config files (the default).
  107. //Locations = ConfigLocations.All;
  108. }
  109. public override void Before (MethodInfo methodUnderTest)
  110. {
  111. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  112. if (AutoInit)
  113. {
  114. #if DEBUG_IDISPOSABLE
  115. // Clear out any lingering Responder instances from previous tests
  116. if (View.Instances.Count == 0)
  117. {
  118. Assert.Empty (View.Instances);
  119. }
  120. else
  121. {
  122. View.Instances.Clear ();
  123. }
  124. #endif
  125. Application.Init ((IConsoleDriver)Activator.CreateInstance (_driverType));
  126. }
  127. }
  128. private bool AutoInit { get; }
  129. }
  130. /// <summary>
  131. /// Enables test functions annotated with the [TestRespondersDisposed] attribute to ensure all Views are disposed.
  132. /// </summary>
  133. /// <remarks>
  134. /// On Before, sets Configuration.Locations to ConfigLocations.DefaultOnly.
  135. /// On After, sets Configuration.Locations to ConfigLocations.All.
  136. /// </remarks>
  137. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
  138. public class TestRespondersDisposed : BeforeAfterTestAttribute
  139. {
  140. public TestRespondersDisposed () { CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US"); }
  141. public override void After (MethodInfo methodUnderTest)
  142. {
  143. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  144. base.After (methodUnderTest);
  145. #if DEBUG_IDISPOSABLE
  146. Assert.Empty (View.Instances);
  147. #endif
  148. }
  149. public override void Before (MethodInfo methodUnderTest)
  150. {
  151. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  152. base.Before (methodUnderTest);
  153. #if DEBUG_IDISPOSABLE
  154. // Clear out any lingering Responder instances from previous tests
  155. View.Instances.Clear ();
  156. Assert.Empty (View.Instances);
  157. #endif
  158. }
  159. }
  160. // TODO: Make this inherit from TestRespondersDisposed so that all tests that don't dispose Views correctly can be identified and fixed
  161. /// <summary>
  162. /// Enables test functions annotated with the [SetupFakeDriver] attribute to set Application.Driver to new
  163. /// FakeDriver(). The driver is set up with 25 rows and columns.
  164. /// </summary>
  165. /// <remarks>
  166. /// On Before, sets Configuration.Locations to ConfigLocations.DefaultOnly.
  167. /// On After, sets Configuration.Locations to ConfigLocations.All.
  168. /// </remarks>
  169. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
  170. public class SetupFakeDriverAttribute : BeforeAfterTestAttribute
  171. {
  172. public override void After (MethodInfo methodUnderTest)
  173. {
  174. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  175. // Turn off diagnostic flags in case some test left them on
  176. View.Diagnostics = ViewDiagnosticFlags.Off;
  177. Application.ResetState (true);
  178. Assert.Null (Application.Driver);
  179. Assert.Equal (new (0, 0, 2048, 2048), Application.Screen);
  180. base.After (methodUnderTest);
  181. }
  182. public override void Before (MethodInfo methodUnderTest)
  183. {
  184. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  185. Application.ResetState (true);
  186. Assert.Null (Application.Driver);
  187. Application.Driver = new FakeDriver { Rows = 25, Cols = 25 };
  188. Assert.Equal (new (0, 0, 25, 25), Application.Screen);
  189. // Ensures subscribing events, at least for the SizeChanged event
  190. Application.SubscribeDriverEvents ();
  191. base.Before (methodUnderTest);
  192. }
  193. }
  194. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
  195. public class TestDateAttribute : BeforeAfterTestAttribute
  196. {
  197. public TestDateAttribute () { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; }
  198. private readonly CultureInfo _currentCulture = CultureInfo.CurrentCulture;
  199. public override void After (MethodInfo methodUnderTest)
  200. {
  201. CultureInfo.CurrentCulture = _currentCulture;
  202. Assert.Equal (CultureInfo.CurrentCulture, _currentCulture);
  203. }
  204. public override void Before (MethodInfo methodUnderTest) { Assert.Equal (CultureInfo.CurrentCulture, CultureInfo.InvariantCulture); }
  205. }
  206. internal partial class TestHelpers
  207. {
  208. private const char SpaceChar = ' ';
  209. private static readonly Rune SpaceRune = (Rune)SpaceChar;
  210. #pragma warning disable xUnit1013 // Public method should be marked as test
  211. /// <summary>
  212. /// Verifies <paramref name="expectedAttributes"/> are found at the locations specified by
  213. /// <paramref name="expectedLook"/>. <paramref name="expectedLook"/> is a bitmap of indexes into
  214. /// <paramref name="expectedAttributes"/> (e.g. "00110" means the attribute at <c>expectedAttributes[1]</c> is expected
  215. /// at the 3rd and 4th columns of the 1st row of driver.Contents).
  216. /// </summary>
  217. /// <param name="expectedLook">
  218. /// Numbers between 0 and 9 for each row/col of the console. Must be valid indexes into
  219. /// <paramref name="expectedAttributes"/>.
  220. /// </param>
  221. /// <param name="output"></param>
  222. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  223. /// <param name="expectedAttributes"></param>
  224. public static void AssertDriverAttributesAre (
  225. string expectedLook,
  226. ITestOutputHelper output,
  227. IConsoleDriver driver = null,
  228. params Attribute [] expectedAttributes
  229. )
  230. {
  231. #pragma warning restore xUnit1013 // Public method should be marked as test
  232. if (expectedAttributes.Length > 10)
  233. {
  234. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  235. }
  236. expectedLook = expectedLook.Trim ();
  237. driver ??= Application.Driver;
  238. Cell [,] contents = driver.Contents;
  239. var line = 0;
  240. foreach (string lineString in expectedLook.Split ('\n').Select (l => l.Trim ()))
  241. {
  242. for (var c = 0; c < lineString.Length; c++)
  243. {
  244. Attribute? val = contents [line, c].Attribute;
  245. List<Attribute> match = expectedAttributes.Where (e => e == val).ToList ();
  246. switch (match.Count)
  247. {
  248. case 0:
  249. output.WriteLine (
  250. $"{Application.ToString (driver)}\n"
  251. + $"Expected Attribute {val} (PlatformColor = {val.Value.PlatformColor}) at Contents[{line},{c}] {contents [line, c]} ((PlatformColor = {contents [line, c].Attribute.Value.PlatformColor}) was not found.\n"
  252. + $" Expected: {string.Join (",", expectedAttributes.Select (c => c))}\n"
  253. + $" But Was: <not found>"
  254. );
  255. Assert.Empty (match);
  256. return;
  257. case > 1:
  258. throw new ArgumentException (
  259. $"Bad value for expectedColors, {match.Count} Attributes had the same Value"
  260. );
  261. }
  262. char colorUsed = Array.IndexOf (expectedAttributes, match [0]).ToString () [0];
  263. char userExpected = lineString [c];
  264. if (colorUsed != userExpected)
  265. {
  266. output.WriteLine ($"{Application.ToString (driver)}");
  267. output.WriteLine ($"Unexpected Attribute at Contents[{line},{c}] {contents [line, c]}.");
  268. output.WriteLine ($" Expected: {userExpected} ({expectedAttributes [int.Parse (userExpected.ToString ())]})");
  269. output.WriteLine ($" But Was: {colorUsed} ({val})");
  270. Assert.Equal (userExpected, colorUsed);
  271. return;
  272. }
  273. }
  274. line++;
  275. }
  276. }
  277. #pragma warning disable xUnit1013 // Public method should be marked as test
  278. /// <summary>Asserts that the driver contents match the expected contents, optionally ignoring any trailing whitespace.</summary>
  279. /// <param name="expectedLook"></param>
  280. /// <param name="output"></param>
  281. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  282. /// <param name="ignoreLeadingWhitespace"></param>
  283. public static void AssertDriverContentsAre (
  284. string expectedLook,
  285. ITestOutputHelper output,
  286. IConsoleDriver driver = null,
  287. bool ignoreLeadingWhitespace = false
  288. )
  289. {
  290. #pragma warning restore xUnit1013 // Public method should be marked as test
  291. var actualLook = Application.ToString (driver ?? Application.Driver);
  292. if (string.Equals (expectedLook, actualLook))
  293. {
  294. return;
  295. }
  296. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  297. expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
  298. actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
  299. if (ignoreLeadingWhitespace)
  300. {
  301. expectedLook = LeadingWhitespaceRegEx ().Replace (expectedLook, "").Trim ();
  302. actualLook = LeadingWhitespaceRegEx ().Replace (actualLook, "").Trim ();
  303. }
  304. // standardize line endings for the comparison
  305. expectedLook = expectedLook.Replace ("\r\n", "\n");
  306. actualLook = actualLook.Replace ("\r\n", "\n");
  307. // If test is about to fail show user what things looked like
  308. if (!string.Equals (expectedLook, actualLook))
  309. {
  310. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  311. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  312. }
  313. Assert.Equal (expectedLook, actualLook);
  314. }
  315. /// <summary>
  316. /// Asserts that the driver contents are equal to the provided string.
  317. /// </summary>
  318. /// <param name="expectedLook"></param>
  319. /// <param name="output"></param>
  320. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  321. /// <returns></returns>
  322. public static Rectangle AssertDriverContentsWithFrameAre (
  323. string expectedLook,
  324. ITestOutputHelper output,
  325. IConsoleDriver driver = null
  326. )
  327. {
  328. List<List<Rune>> lines = new ();
  329. var sb = new StringBuilder ();
  330. driver ??= Application.Driver;
  331. int x = -1;
  332. int y = -1;
  333. int w = -1;
  334. int h = -1;
  335. Cell [,] contents = driver.Contents;
  336. for (var rowIndex = 0; rowIndex < driver.Rows; rowIndex++)
  337. {
  338. List<Rune> runes = [];
  339. for (var colIndex = 0; colIndex < driver.Cols; colIndex++)
  340. {
  341. Rune runeAtCurrentLocation = contents [rowIndex, colIndex].Rune;
  342. if (runeAtCurrentLocation != SpaceRune)
  343. {
  344. if (x == -1)
  345. {
  346. x = colIndex;
  347. y = rowIndex;
  348. for (var i = 0; i < colIndex; i++)
  349. {
  350. runes.InsertRange (i, [SpaceRune]);
  351. }
  352. }
  353. if (runeAtCurrentLocation.GetColumns () > 1)
  354. {
  355. colIndex++;
  356. }
  357. if (colIndex + 1 > w)
  358. {
  359. w = colIndex + 1;
  360. }
  361. h = rowIndex - y + 1;
  362. }
  363. if (x > -1)
  364. {
  365. runes.Add (runeAtCurrentLocation);
  366. }
  367. // See Issue #2616
  368. //foreach (var combMark in contents [r, c].CombiningMarks) {
  369. // runes.Add (combMark);
  370. //}
  371. }
  372. if (runes.Count > 0)
  373. {
  374. lines.Add (runes);
  375. }
  376. }
  377. // Remove unnecessary empty lines
  378. if (lines.Count > 0)
  379. {
  380. for (int r = lines.Count - 1; r > h - 1; r--)
  381. {
  382. lines.RemoveAt (r);
  383. }
  384. }
  385. // Remove trailing whitespace on each line
  386. foreach (List<Rune> row in lines)
  387. {
  388. for (int c = row.Count - 1; c >= 0; c--)
  389. {
  390. Rune rune = row [c];
  391. if (rune != (Rune)' ' || row.Sum (x => x.GetColumns ()) == w)
  392. {
  393. break;
  394. }
  395. row.RemoveAt (c);
  396. }
  397. }
  398. // Convert Rune list to string
  399. for (var r = 0; r < lines.Count; r++)
  400. {
  401. var line = StringExtensions.ToString (lines [r]);
  402. if (r == lines.Count - 1)
  403. {
  404. sb.Append (line);
  405. }
  406. else
  407. {
  408. sb.AppendLine (line);
  409. }
  410. }
  411. var actualLook = sb.ToString ();
  412. if (string.Equals (expectedLook, actualLook))
  413. {
  414. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  415. }
  416. // standardize line endings for the comparison
  417. expectedLook = expectedLook.ReplaceLineEndings ();
  418. actualLook = actualLook.ReplaceLineEndings ();
  419. // Remove the first and the last line ending from the expectedLook
  420. if (expectedLook.StartsWith (Environment.NewLine))
  421. {
  422. expectedLook = expectedLook [Environment.NewLine.Length..];
  423. }
  424. if (expectedLook.EndsWith (Environment.NewLine))
  425. {
  426. expectedLook = expectedLook [..^Environment.NewLine.Length];
  427. }
  428. // If test is about to fail show user what things looked like
  429. if (!string.Equals (expectedLook, actualLook))
  430. {
  431. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  432. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  433. }
  434. Assert.Equal (expectedLook, actualLook);
  435. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  436. }
  437. #pragma warning disable xUnit1013 // Public method should be marked as test
  438. /// <summary>
  439. /// Verifies two strings are equivalent. If the assert fails, output will be generated to standard output showing
  440. /// the expected and actual look.
  441. /// </summary>
  442. /// <param name="output"></param>
  443. /// <param name="expectedLook">
  444. /// A string containing the expected look. Newlines should be specified as "\r\n" as they will
  445. /// be converted to <see cref="Environment.NewLine"/> to make tests platform independent.
  446. /// </param>
  447. /// <param name="actualLook"></param>
  448. public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
  449. {
  450. // Convert newlines to platform-specific newlines
  451. expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
  452. // If test is about to fail show user what things looked like
  453. if (!string.Equals (expectedLook, actualLook))
  454. {
  455. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  456. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  457. }
  458. Assert.Equal (expectedLook, actualLook);
  459. }
  460. #pragma warning restore xUnit1013 // Public method should be marked as test
  461. public static View CreateViewFromType (Type type, ConstructorInfo ctor)
  462. {
  463. View viewType = null;
  464. if (type.IsGenericType && type.IsTypeDefinition)
  465. {
  466. List<Type> gTypes = new ();
  467. foreach (Type args in type.GetGenericArguments ())
  468. {
  469. gTypes.Add (typeof (object));
  470. }
  471. type = type.MakeGenericType (gTypes.ToArray ());
  472. Assert.IsType (type, (View)Activator.CreateInstance (type));
  473. }
  474. else
  475. {
  476. ParameterInfo [] paramsInfo = ctor.GetParameters ();
  477. Type paramType;
  478. List<object> pTypes = new ();
  479. if (type.IsGenericType)
  480. {
  481. foreach (Type args in type.GetGenericArguments ())
  482. {
  483. paramType = args.GetType ();
  484. if (args.Name == "T")
  485. {
  486. pTypes.Add (typeof (object));
  487. }
  488. else
  489. {
  490. AddArguments (paramType, pTypes);
  491. }
  492. }
  493. }
  494. foreach (ParameterInfo p in paramsInfo)
  495. {
  496. paramType = p.ParameterType;
  497. if (p.HasDefaultValue)
  498. {
  499. pTypes.Add (p.DefaultValue);
  500. }
  501. else
  502. {
  503. AddArguments (paramType, pTypes);
  504. }
  505. }
  506. if (type.IsGenericType && !type.IsTypeDefinition)
  507. {
  508. viewType = (View)Activator.CreateInstance (type);
  509. Assert.IsType (type, viewType);
  510. }
  511. else
  512. {
  513. viewType = (View)ctor.Invoke (pTypes.ToArray ());
  514. Assert.IsType (type, viewType);
  515. }
  516. }
  517. return viewType;
  518. }
  519. public static List<Type> GetAllViewClasses ()
  520. {
  521. return typeof (View).Assembly.GetTypes ()
  522. .Where (
  523. myType => myType.IsClass
  524. && !myType.IsAbstract
  525. && myType.IsPublic
  526. && myType.IsSubclassOf (typeof (View))
  527. )
  528. .ToList ();
  529. }
  530. /// <summary>
  531. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering. If one or more of the
  532. /// expected colors are not used then the failure will output both the colors that were found to be used and which of
  533. /// your expectations was not met.
  534. /// </summary>
  535. /// <param name="driver">if null uses <see cref="Application.Driver"/></param>
  536. /// <param name="expectedColors"></param>
  537. internal static void AssertDriverUsedColors (IConsoleDriver driver = null, params Attribute [] expectedColors)
  538. {
  539. driver ??= Application.Driver;
  540. Cell [,] contents = driver.Contents;
  541. List<Attribute> toFind = expectedColors.ToList ();
  542. // Contents 3rd column is an Attribute
  543. HashSet<Attribute> colorsUsed = new ();
  544. for (var r = 0; r < driver.Rows; r++)
  545. {
  546. for (var c = 0; c < driver.Cols; c++)
  547. {
  548. Attribute? val = contents [r, c].Attribute;
  549. if (val.HasValue)
  550. {
  551. colorsUsed.Add (val.Value);
  552. Attribute match = toFind.FirstOrDefault (e => e == val);
  553. // need to check twice because Attribute is a struct and therefore cannot be null
  554. if (toFind.Any (e => e == val))
  555. {
  556. toFind.Remove (match);
  557. }
  558. }
  559. }
  560. }
  561. if (!toFind.Any ())
  562. {
  563. return;
  564. }
  565. var sb = new StringBuilder ();
  566. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
  567. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
  568. throw new (sb.ToString ());
  569. }
  570. private static void AddArguments (Type paramType, List<object> pTypes)
  571. {
  572. if (paramType == typeof (Rectangle))
  573. {
  574. pTypes.Add (Rectangle.Empty);
  575. }
  576. else if (paramType == typeof (string))
  577. {
  578. pTypes.Add (string.Empty);
  579. }
  580. else if (paramType == typeof (int))
  581. {
  582. pTypes.Add (0);
  583. }
  584. else if (paramType == typeof (bool))
  585. {
  586. pTypes.Add (true);
  587. }
  588. else if (paramType.Name == "IList")
  589. {
  590. pTypes.Add (new List<object> ());
  591. }
  592. else if (paramType.Name == "View")
  593. {
  594. var top = new Toplevel ();
  595. var view = new View ();
  596. top.Add (view);
  597. pTypes.Add (view);
  598. }
  599. else if (paramType.Name == "View[]")
  600. {
  601. pTypes.Add (new View [] { });
  602. }
  603. else if (paramType.Name == "Stream")
  604. {
  605. pTypes.Add (new MemoryStream ());
  606. }
  607. else if (paramType.Name == "String")
  608. {
  609. pTypes.Add (string.Empty);
  610. }
  611. else if (paramType.Name == "TreeView`1[T]")
  612. {
  613. pTypes.Add (string.Empty);
  614. }
  615. else
  616. {
  617. pTypes.Add (null);
  618. }
  619. }
  620. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  621. private static partial Regex LeadingWhitespaceRegEx ();
  622. private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
  623. {
  624. string replaced = toReplace;
  625. replaced = Environment.NewLine.Length switch
  626. {
  627. 2 when !replaced.Contains ("\r\n") => replaced.Replace ("\n", Environment.NewLine),
  628. 1 => replaced.Replace ("\r\n", Environment.NewLine),
  629. var _ => replaced
  630. };
  631. return replaced;
  632. }
  633. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  634. private static partial Regex TrailingWhiteSpaceRegEx ();
  635. }
  636. public class TestsAllViews
  637. {
  638. public static IEnumerable<object []> AllViewTypes =>
  639. typeof (View).Assembly
  640. .GetTypes ()
  641. .Where (type => type.IsClass && !type.IsAbstract && type.IsPublic && (type.IsSubclassOf (typeof (View)) || type == typeof (View)))
  642. .Select (type => new object [] { type });
  643. public static View CreateInstanceIfNotGeneric (Type type)
  644. {
  645. if (type.IsGenericType)
  646. {
  647. // Return null for generic types
  648. return null;
  649. }
  650. return Activator.CreateInstance (type) as View;
  651. }
  652. }