ScenarioTests.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. using System.Collections.ObjectModel;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using Xunit.Abstractions;
  5. namespace UICatalog.Tests;
  6. public class ScenarioTests : TestsAllViews
  7. {
  8. public ScenarioTests (ITestOutputHelper output)
  9. {
  10. #if DEBUG_IDISPOSABLE
  11. Responder.Instances.Clear ();
  12. #endif
  13. _output = output;
  14. }
  15. private readonly ITestOutputHelper _output;
  16. private object _timeoutLock;
  17. /// <summary>
  18. /// <para>This runs through all Scenarios defined in UI Catalog, calling Init, Setup, and Run.</para>
  19. /// <para>Should find any Scenarios which crash on load or do not respond to <see cref="Application.RequestStop()"/>.</para>
  20. /// </summary>
  21. [Theory]
  22. [MemberData (nameof (AllScenarioTypes))]
  23. public void All_Scenarios_Quit_And_Init_Shutdown_Properly (Type scenarioType)
  24. {
  25. Assert.Null (_timeoutLock);
  26. _timeoutLock = new ();
  27. // Disable any UIConfig settings
  28. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  29. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  30. // If a previous test failed, this will ensure that the Application is in a clean state
  31. Application.ResetState (true);
  32. _output.WriteLine ($"Running Scenario '{scenarioType}'");
  33. var scenario = (Scenario)Activator.CreateInstance (scenarioType);
  34. uint abortTime = 1500;
  35. object timeout = null;
  36. var initialized = false;
  37. var shutdown = false;
  38. int iterationCount = 0;
  39. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  40. Application.ForceDriver = "FakeDriver";
  41. scenario.Main ();
  42. scenario.Dispose ();
  43. scenario = null;
  44. Application.ForceDriver = string.Empty;
  45. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  46. lock (_timeoutLock)
  47. {
  48. if (timeout is { })
  49. {
  50. timeout = null;
  51. }
  52. }
  53. Assert.True (initialized);
  54. Assert.True (shutdown);
  55. #if DEBUG_IDISPOSABLE
  56. Assert.Empty (Responder.Instances);
  57. #endif
  58. lock (_timeoutLock)
  59. {
  60. _timeoutLock = null;
  61. }
  62. // Restore the configuration locations
  63. ConfigurationManager.Locations = savedConfigLocations;
  64. ConfigurationManager.Reset ();
  65. return;
  66. void OnApplicationOnInitializedChanged (object s, EventArgs<bool> a)
  67. {
  68. if (a.CurrentValue)
  69. {
  70. Application.Iteration += OnApplicationOnIteration;
  71. initialized = true;
  72. lock (_timeoutLock)
  73. {
  74. timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  75. }
  76. }
  77. else
  78. {
  79. Application.Iteration -= OnApplicationOnIteration;
  80. shutdown = true;
  81. }
  82. _output.WriteLine ($"Initialized == {a.CurrentValue}");
  83. }
  84. // If the scenario doesn't close within 500ms, this will force it to quit
  85. bool ForceCloseCallback ()
  86. {
  87. lock (_timeoutLock)
  88. {
  89. if (timeout is { })
  90. {
  91. timeout = null;
  92. }
  93. }
  94. Assert.Fail (
  95. $"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey} after {abortTime}ms and {iterationCount} iterations. Force quit.");
  96. // Restore the configuration locations
  97. ConfigurationManager.Locations = savedConfigLocations;
  98. ConfigurationManager.Reset ();
  99. Application.ResetState (true);
  100. return false;
  101. }
  102. void OnApplicationOnIteration (object s, IterationEventArgs a)
  103. {
  104. iterationCount++;
  105. if (Application.Initialized)
  106. {
  107. // Press QuitKey
  108. _output.WriteLine ($"Attempting to quit with {Application.QuitKey}");
  109. Application.RaiseKeyDownEvent (Application.QuitKey);
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// <para>This runs through all Scenarios defined in UI Catalog, calling Init, Setup, and Run and measuring the perf of each.</para>
  115. /// </summary>
  116. [Theory]
  117. [MemberData (nameof (AllScenarioTypes))]
  118. public void All_Scenarios_Time (Type scenarioType)
  119. {
  120. Assert.Null (_timeoutLock);
  121. _timeoutLock = new ();
  122. // Disable any UIConfig settings
  123. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  124. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  125. // If a previous test failed, this will ensure that the Application is in a clean state
  126. Application.ResetState (true);
  127. uint maxIterations = 1000;
  128. uint abortTime = 2000;
  129. object timeout = null;
  130. var initialized = false;
  131. var shutdown = false;
  132. int iterationCount = 0;
  133. int clearedContentCount = 0;
  134. int refreshedCount = 0;
  135. int updatedCount = 0;
  136. int drawCompleteCount = 0;
  137. int laidOutCount = 0;
  138. _output.WriteLine ($"Running Scenario '{scenarioType}'");
  139. var scenario = (Scenario)Activator.CreateInstance (scenarioType);
  140. Stopwatch stopwatch = null;
  141. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  142. Application.ForceDriver = "FakeDriver";
  143. scenario!.Main ();
  144. scenario.Dispose ();
  145. scenario = null;
  146. Application.ForceDriver = string.Empty;
  147. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  148. lock (_timeoutLock)
  149. {
  150. if (timeout is { })
  151. {
  152. timeout = null;
  153. }
  154. }
  155. lock (_timeoutLock)
  156. {
  157. _timeoutLock = null;
  158. }
  159. _output.WriteLine ($"Scenario {scenarioType}");
  160. _output.WriteLine ($" took {stopwatch.ElapsedMilliseconds} ms to run.");
  161. _output.WriteLine ($" called Driver.ClearContents {clearedContentCount} times.");
  162. _output.WriteLine ($" called Driver.Refresh {refreshedCount} times.");
  163. _output.WriteLine ($" which updated the screen {updatedCount} times.");
  164. _output.WriteLine ($" called View.Draw {drawCompleteCount} times.");
  165. _output.WriteLine ($" called View.LayoutComplete {laidOutCount} times.");
  166. // Restore the configuration locations
  167. ConfigurationManager.Locations = savedConfigLocations;
  168. ConfigurationManager.Reset ();
  169. return;
  170. void OnApplicationOnInitializedChanged (object s, EventArgs<bool> a)
  171. {
  172. if (a.CurrentValue)
  173. {
  174. lock (_timeoutLock)
  175. {
  176. timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  177. }
  178. initialized = true;
  179. Application.Iteration += OnApplicationOnIteration;
  180. Application.Driver!.ClearedContents += (sender, args) => clearedContentCount++;
  181. Application.Driver!.Refreshed += (sender, args) =>
  182. {
  183. refreshedCount++;
  184. if (args.CurrentValue)
  185. {
  186. updatedCount++;
  187. }
  188. };
  189. Application.NotifyNewRunState += OnApplicationNotifyNewRunState;
  190. stopwatch = Stopwatch.StartNew ();
  191. }
  192. else
  193. {
  194. shutdown = true;
  195. Application.NotifyNewRunState -= OnApplicationNotifyNewRunState;
  196. Application.Iteration -= OnApplicationOnIteration;
  197. stopwatch!.Stop ();
  198. }
  199. _output.WriteLine ($"Initialized == {a.CurrentValue}");
  200. }
  201. void OnApplicationOnIteration (object s, IterationEventArgs a)
  202. {
  203. iterationCount++;
  204. if (iterationCount > maxIterations)
  205. {
  206. // Press QuitKey
  207. _output.WriteLine ($"Attempting to quit scenario with RequestStop");
  208. Application.RequestStop ();
  209. }
  210. }
  211. void OnApplicationNotifyNewRunState (object sender, RunStateEventArgs e)
  212. {
  213. // Get a list of all subviews under Application.Top (and their subviews, etc.)
  214. // and subscribe to their DrawComplete event
  215. void SubscribeAllSubviews (View view)
  216. {
  217. view.DrawComplete += (s, a) => drawCompleteCount++;
  218. view.SubviewsLaidOut += (s, a) => laidOutCount++;
  219. foreach (View subview in view.Subviews)
  220. {
  221. SubscribeAllSubviews (subview);
  222. }
  223. }
  224. SubscribeAllSubviews (Application.Top);
  225. }
  226. // If the scenario doesn't close within the abort time, this will force it to quit
  227. bool ForceCloseCallback ()
  228. {
  229. lock (_timeoutLock)
  230. {
  231. if (timeout is { })
  232. {
  233. timeout = null;
  234. }
  235. }
  236. _output.WriteLine(
  237. $"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey} after {abortTime}ms and {iterationCount} iterations. Force quit.");
  238. Application.RequestStop ();
  239. return false;
  240. }
  241. }
  242. public static IEnumerable<object []> AllScenarioTypes =>
  243. typeof (Scenario).Assembly
  244. .GetTypes ()
  245. .Where (type => type.IsClass && !type.IsAbstract && type.IsSubclassOf (typeof (Scenario)))
  246. .Select (type => new object [] { type });
  247. [Fact]
  248. public void Run_All_Views_Tester_Scenario ()
  249. {
  250. // Disable any UIConfig settings
  251. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  252. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  253. Window _leftPane;
  254. ListView _classListView;
  255. FrameView _hostPane;
  256. Dictionary<string, Type> _viewClasses;
  257. View _curView = null;
  258. // Settings
  259. FrameView _settingsPane;
  260. FrameView _locationFrame;
  261. RadioGroup _xRadioGroup;
  262. TextField _xText;
  263. var _xVal = 0;
  264. RadioGroup _yRadioGroup;
  265. TextField _yText;
  266. var _yVal = 0;
  267. FrameView _sizeFrame;
  268. RadioGroup _wRadioGroup;
  269. TextField _wText;
  270. var _wVal = 0;
  271. RadioGroup _hRadioGroup;
  272. TextField _hText;
  273. var _hVal = 0;
  274. List<string> posNames = new () { "Percent", "AnchorEnd", "Center", "Absolute" };
  275. List<string> dimNames = new () { "Auto", "Percent", "Fill", "Absolute" };
  276. Application.Init (new FakeDriver ());
  277. var top = new Toplevel ();
  278. _viewClasses = TestHelpers.GetAllViewClasses ().ToDictionary (t => t.Name);
  279. _leftPane = new ()
  280. {
  281. Title = "Classes",
  282. X = 0,
  283. Y = 0,
  284. Width = 15,
  285. Height = Dim.Fill (1), // for status bar
  286. CanFocus = false,
  287. ColorScheme = Colors.ColorSchemes ["TopLevel"]
  288. };
  289. _classListView = new ()
  290. {
  291. X = 0,
  292. Y = 0,
  293. Width = Dim.Fill (),
  294. Height = Dim.Fill (),
  295. AllowsMarking = false,
  296. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  297. Source = new ListWrapper<string> (new (_viewClasses.Keys.ToList ()))
  298. };
  299. _leftPane.Add (_classListView);
  300. _settingsPane = new ()
  301. {
  302. X = Pos.Right (_leftPane),
  303. Y = 0, // for menu
  304. Width = Dim.Fill (),
  305. Height = 10,
  306. CanFocus = false,
  307. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  308. Title = "Settings"
  309. };
  310. var radioItems = new [] { "Percent(x)", "AnchorEnd(x)", "Center", "Absolute(x)" };
  311. _locationFrame = new ()
  312. {
  313. X = 0,
  314. Y = 0,
  315. Height = 3 + radioItems.Length,
  316. Width = 36,
  317. Title = "Location (Pos)"
  318. };
  319. _settingsPane.Add (_locationFrame);
  320. var label = new Label { X = 0, Y = 0, Text = "x:" };
  321. _locationFrame.Add (label);
  322. _xRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  323. _xText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_xVal}" };
  324. _locationFrame.Add (_xText);
  325. _locationFrame.Add (_xRadioGroup);
  326. radioItems = new [] { "Percent(y)", "AnchorEnd(y)", "Center", "Absolute(y)" };
  327. label = new () { X = Pos.Right (_xRadioGroup) + 1, Y = 0, Text = "y:" };
  328. _locationFrame.Add (label);
  329. _yText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_yVal}" };
  330. _locationFrame.Add (_yText);
  331. _yRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  332. _locationFrame.Add (_yRadioGroup);
  333. _sizeFrame = new ()
  334. {
  335. X = Pos.Right (_locationFrame),
  336. Y = Pos.Y (_locationFrame),
  337. Height = 3 + radioItems.Length,
  338. Width = 40,
  339. Title = "Size (Dim)"
  340. };
  341. radioItems = new [] { "Auto()", "Percent(width)", "Fill(width)", "Absolute(width)" };
  342. label = new () { X = 0, Y = 0, Text = "width:" };
  343. _sizeFrame.Add (label);
  344. _wRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  345. _wText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_wVal}" };
  346. _sizeFrame.Add (_wText);
  347. _sizeFrame.Add (_wRadioGroup);
  348. radioItems = new [] { "Auto()", "Percent(height)", "Fill(height)", "Absolute(height)" };
  349. label = new () { X = Pos.Right (_wRadioGroup) + 1, Y = 0, Text = "height:" };
  350. _sizeFrame.Add (label);
  351. _hText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_hVal}" };
  352. _sizeFrame.Add (_hText);
  353. _hRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  354. _sizeFrame.Add (_hRadioGroup);
  355. _settingsPane.Add (_sizeFrame);
  356. _hostPane = new ()
  357. {
  358. X = Pos.Right (_leftPane),
  359. Y = Pos.Bottom (_settingsPane),
  360. Width = Dim.Fill (),
  361. Height = Dim.Fill (1), // + 1 for status bar
  362. ColorScheme = Colors.ColorSchemes ["Dialog"]
  363. };
  364. _classListView.OpenSelectedItem += (s, a) => { _settingsPane.SetFocus (); };
  365. _classListView.SelectedItemChanged += (s, args) =>
  366. {
  367. // Remove existing class, if any
  368. if (_curView != null)
  369. {
  370. _curView.SubviewsLaidOut -= LayoutCompleteHandler;
  371. _hostPane.Remove (_curView);
  372. _curView.Dispose ();
  373. _curView = null;
  374. _hostPane.FillRect (_hostPane.Viewport);
  375. }
  376. _curView = CreateClass (_viewClasses.Values.ToArray () [_classListView.SelectedItem]);
  377. };
  378. _xRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  379. _xText.TextChanged += (s, args) =>
  380. {
  381. try
  382. {
  383. _xVal = int.Parse (_xText.Text);
  384. DimPosChanged (_curView);
  385. }
  386. catch
  387. { }
  388. };
  389. _yText.TextChanged += (s, e) =>
  390. {
  391. try
  392. {
  393. _yVal = int.Parse (_yText.Text);
  394. DimPosChanged (_curView);
  395. }
  396. catch
  397. { }
  398. };
  399. _yRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  400. _wRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  401. _wText.TextChanged += (s, args) =>
  402. {
  403. try
  404. {
  405. _wVal = int.Parse (_wText.Text);
  406. DimPosChanged (_curView);
  407. }
  408. catch
  409. { }
  410. };
  411. _hText.TextChanged += (s, args) =>
  412. {
  413. try
  414. {
  415. _hVal = int.Parse (_hText.Text);
  416. DimPosChanged (_curView);
  417. }
  418. catch
  419. { }
  420. };
  421. _hRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  422. top.Add (_leftPane, _settingsPane, _hostPane);
  423. top.LayoutSubviews ();
  424. _curView = CreateClass (_viewClasses.First ().Value);
  425. var iterations = 0;
  426. Application.Iteration += (s, a) =>
  427. {
  428. iterations++;
  429. if (iterations < _viewClasses.Count)
  430. {
  431. _classListView.MoveDown ();
  432. Assert.Equal (
  433. _curView.GetType ().Name,
  434. _viewClasses.Values.ToArray () [_classListView.SelectedItem].Name
  435. );
  436. }
  437. else
  438. {
  439. Application.RequestStop ();
  440. }
  441. };
  442. Application.Run (top);
  443. Assert.Equal (_viewClasses.Count, iterations);
  444. top.Dispose ();
  445. Application.Shutdown ();
  446. // Restore the configuration locations
  447. ConfigurationManager.Locations = savedConfigLocations;
  448. ConfigurationManager.Reset ();
  449. void DimPosChanged (View view)
  450. {
  451. if (view == null)
  452. {
  453. return;
  454. }
  455. try
  456. {
  457. switch (_xRadioGroup.SelectedItem)
  458. {
  459. case 0:
  460. view.X = Pos.Percent (_xVal);
  461. break;
  462. case 1:
  463. view.X = Pos.AnchorEnd (_xVal);
  464. break;
  465. case 2:
  466. view.X = Pos.Center ();
  467. break;
  468. case 3:
  469. view.X = Pos.Absolute (_xVal);
  470. break;
  471. }
  472. switch (_yRadioGroup.SelectedItem)
  473. {
  474. case 0:
  475. view.Y = Pos.Percent (_yVal);
  476. break;
  477. case 1:
  478. view.Y = Pos.AnchorEnd (_yVal);
  479. break;
  480. case 2:
  481. view.Y = Pos.Center ();
  482. break;
  483. case 3:
  484. view.Y = Pos.Absolute (_yVal);
  485. break;
  486. }
  487. switch (_wRadioGroup.SelectedItem)
  488. {
  489. case 0:
  490. view.Width = Dim.Percent (_wVal);
  491. break;
  492. case 1:
  493. view.Width = Dim.Fill (_wVal);
  494. break;
  495. case 2:
  496. view.Width = Dim.Absolute (_wVal);
  497. break;
  498. }
  499. switch (_hRadioGroup.SelectedItem)
  500. {
  501. case 0:
  502. view.Height = Dim.Percent (_hVal);
  503. break;
  504. case 1:
  505. view.Height = Dim.Fill (_hVal);
  506. break;
  507. case 2:
  508. view.Height = Dim.Absolute (_hVal);
  509. break;
  510. }
  511. }
  512. catch (Exception e)
  513. {
  514. MessageBox.ErrorQuery ("Exception", e.Message, "Ok");
  515. }
  516. UpdateTitle (view);
  517. }
  518. void UpdateSettings (View view)
  519. {
  520. var x = view.X.ToString ();
  521. var y = view.Y.ToString ();
  522. try
  523. {
  524. _xRadioGroup.SelectedItem = posNames.IndexOf (posNames.First (s => x.Contains (s)));
  525. _yRadioGroup.SelectedItem = posNames.IndexOf (posNames.First (s => y.Contains (s)));
  526. }
  527. catch (InvalidOperationException e)
  528. {
  529. // This is a hack to work around the fact that the Pos enum doesn't have an "Align" value yet
  530. Debug.WriteLine ($"{e}");
  531. }
  532. _xText.Text = $"{view.Frame.X}";
  533. _yText.Text = $"{view.Frame.Y}";
  534. var w = view.Width.ToString ();
  535. var h = view.Height.ToString ();
  536. _wRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.First (s => w.Contains (s)));
  537. _hRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.First (s => h.Contains (s)));
  538. _wText.Text = $"{view.Frame.Width}";
  539. _hText.Text = $"{view.Frame.Height}";
  540. }
  541. void UpdateTitle (View view) { _hostPane.Title = $"{view.GetType ().Name} - {view.X}, {view.Y}, {view.Width}, {view.Height}"; }
  542. View CreateClass (Type type)
  543. {
  544. // If we are to create a generic Type
  545. if (type.IsGenericType)
  546. {
  547. // For each of the <T> arguments
  548. List<Type> typeArguments = new ();
  549. // use <object>
  550. foreach (Type arg in type.GetGenericArguments ())
  551. {
  552. typeArguments.Add (typeof (object));
  553. }
  554. // And change what type we are instantiating from MyClass<T> to MyClass<object>
  555. type = type.MakeGenericType (typeArguments.ToArray ());
  556. }
  557. // Instantiate view
  558. var view = (View)Activator.CreateInstance (type);
  559. if (view is null)
  560. {
  561. return null;
  562. }
  563. if (view.Width is not DimAuto)
  564. {
  565. view.Width = Dim.Percent (75);
  566. }
  567. if (view.Height is not DimAuto)
  568. {
  569. view.Height = Dim.Percent (75);
  570. }
  571. // Set the colorscheme to make it stand out if is null by default
  572. view.ColorScheme ??= Colors.ColorSchemes ["Base"];
  573. // If the view supports a Text property, set it so we have something to look at
  574. if (view.GetType ().GetProperty ("Text") != null)
  575. {
  576. try
  577. {
  578. view.GetType ().GetProperty ("Text")?.GetSetMethod ()?.Invoke (view, new [] { "Test Text" });
  579. }
  580. catch (TargetInvocationException e)
  581. {
  582. MessageBox.ErrorQuery ("Exception", e.InnerException.Message, "Ok");
  583. view = null;
  584. }
  585. }
  586. // If the view supports a Title property, set it so we have something to look at
  587. if (view != null && view.GetType ().GetProperty ("Title") != null)
  588. {
  589. if (view.GetType ().GetProperty ("Title").PropertyType == typeof (string))
  590. {
  591. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  592. }
  593. else
  594. {
  595. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  596. }
  597. }
  598. // If the view supports a Source property, set it so we have something to look at
  599. if (view != null
  600. && view.GetType ().GetProperty ("Source") != null
  601. && view.GetType ().GetProperty ("Source").PropertyType == typeof (IListDataSource))
  602. {
  603. ListWrapper<string> source = new (["Test Text #1", "Test Text #2", "Test Text #3"]);
  604. view?.GetType ().GetProperty ("Source")?.GetSetMethod ()?.Invoke (view, new [] { source });
  605. }
  606. // Add
  607. _hostPane.Add (view);
  608. //DimPosChanged ();
  609. _hostPane.LayoutSubviews ();
  610. _hostPane.ClearViewport ();
  611. _hostPane.SetNeedsDraw ();
  612. UpdateSettings (view);
  613. UpdateTitle (view);
  614. view.SubviewsLaidOut += LayoutCompleteHandler;
  615. return view;
  616. }
  617. void LayoutCompleteHandler (object sender, LayoutEventArgs args) { UpdateTitle (_curView); }
  618. }
  619. [Fact]
  620. public void Run_Generic ()
  621. {
  622. // Disable any UIConfig settings
  623. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  624. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  625. ObservableCollection<Scenario> scenarios = Scenario.GetScenarios ();
  626. Assert.NotEmpty (scenarios);
  627. int item = scenarios.IndexOf (s => s.GetName ().Equals ("Generic", StringComparison.OrdinalIgnoreCase));
  628. Scenario generic = scenarios [item];
  629. Application.Init (new FakeDriver ());
  630. // BUGBUG: (#2474) For some reason ReadKey is not returning the QuitKey for some Scenarios
  631. // by adding this Space it seems to work.
  632. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  633. var ms = 100;
  634. var abortCount = 0;
  635. Func<bool> abortCallback = () =>
  636. {
  637. abortCount++;
  638. _output.WriteLine ($"'Generic' abortCount {abortCount}");
  639. Application.RequestStop ();
  640. return false;
  641. };
  642. var iterations = 0;
  643. object token = null;
  644. Application.Iteration += (s, a) =>
  645. {
  646. if (token == null)
  647. {
  648. // Timeout only must start at first iteration
  649. token = Application.MainLoop.AddTimeout (TimeSpan.FromMilliseconds (ms), abortCallback);
  650. }
  651. iterations++;
  652. _output.WriteLine ($"'Generic' iteration {iterations}");
  653. // Stop if we run out of control...
  654. if (iterations == 10)
  655. {
  656. _output.WriteLine ("'Generic' had to be force quit!");
  657. Application.RequestStop ();
  658. }
  659. };
  660. Application.KeyDown += (sender, args) =>
  661. {
  662. Assert.Equal (Application.QuitKey, args.KeyCode);
  663. };
  664. generic.Main ();
  665. Assert.Equal (0, abortCount);
  666. // # of key up events should match # of iterations
  667. Assert.Equal (1, iterations);
  668. generic.Dispose ();
  669. // Shutdown must be called to safely clean up Application if Init has been called
  670. Application.Shutdown ();
  671. // Restore the configuration locations
  672. ConfigurationManager.Locations = savedConfigLocations;
  673. ConfigurationManager.Reset ();
  674. #if DEBUG_IDISPOSABLE
  675. Assert.Empty (Responder.Instances);
  676. #endif
  677. }
  678. private int CreateInput (string input)
  679. {
  680. FakeConsole.MockKeyPresses.Clear ();
  681. // Put a QuitKey in at the end
  682. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  683. foreach (char c in input.Reverse ())
  684. {
  685. var key = KeyCode.Null;
  686. if (char.IsLetter (c))
  687. {
  688. key = (KeyCode)char.ToUpper (c) | (char.IsUpper (c) ? KeyCode.ShiftMask : 0);
  689. }
  690. else
  691. {
  692. key = (KeyCode)c;
  693. }
  694. FakeConsole.PushMockKeyPress (key);
  695. }
  696. return FakeConsole.MockKeyPresses.Count;
  697. }
  698. }