TestHelpers.cs 26 KB

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