TestHelpers.cs 29 KB

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