TestHelpers.cs 30 KB

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