TestHelpers.cs 30 KB

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