TestHelpers.cs 26 KB

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