TestHelpers.cs 29 KB

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