ScenarioTests.cs 27 KB

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