2
0

TestHelpers.cs 27 KB

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