TestHelpers.cs 27 KB

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