TestHelpers.cs 28 KB

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