TestHelpers.cs 25 KB

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