TestHelpers.cs 27 KB

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