TestHelpers.cs 26 KB

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