TestHelpers.cs 26 KB

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