TestHelpers.cs 30 KB

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