ScenarioTests.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using System.Reflection;
  2. using Xunit.Abstractions;
  3. namespace UICatalog.Tests;
  4. public class ScenarioTests : TestsAllViews
  5. {
  6. private readonly ITestOutputHelper _output;
  7. public ScenarioTests (ITestOutputHelper output)
  8. {
  9. #if DEBUG_IDISPOSABLE
  10. Responder.Instances.Clear ();
  11. #endif
  12. _output = output;
  13. }
  14. public static IEnumerable<object []> AllScenarioTypes =>
  15. typeof (Scenario).Assembly
  16. .GetTypes ()
  17. .Where (type => type.IsClass && !type.IsAbstract && type.IsSubclassOf (typeof (Scenario)))
  18. .Select (type => new object [] { type });
  19. /// <summary>
  20. /// <para>This runs through all Scenarios defined in UI Catalog, calling Init, Setup, and Run.</para>
  21. /// <para>Should find any Scenarios which crash on load or do not respond to <see cref="Application.RequestStop()"/>.</para>
  22. /// </summary>
  23. [Theory]
  24. [MemberData (nameof (AllScenarioTypes))]
  25. public void Run_All_Scenarios (Type scenarioType)
  26. {
  27. _output.WriteLine ($"Running Scenario '{scenarioType}'");
  28. Scenario scenario = (Scenario)Activator.CreateInstance (scenarioType);
  29. Application.Init (new FakeDriver ());
  30. // Press QuitKey
  31. Assert.Empty (FakeConsole.MockKeyPresses);
  32. // BUGBUG: (#2474) For some reason ReadKey is not returning the QuitKey for some Scenarios
  33. // by adding this Space it seems to work.
  34. //FakeConsole.PushMockKeyPress (Key.Space);
  35. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  36. // The only key we care about is the QuitKey
  37. Application.KeyDown += (sender, args) =>
  38. {
  39. _output.WriteLine ($" Keypress: {args.KeyCode}");
  40. // BUGBUG: (#2474) For some reason ReadKey is not returning the QuitKey for some Scenarios
  41. // by adding this Space it seems to work.
  42. // See #2474 for why this is commented out
  43. Assert.Equal (Application.QuitKey.KeyCode, args.KeyCode);
  44. };
  45. uint abortTime = 500;
  46. // If the scenario doesn't close within 500ms, this will force it to quit
  47. bool ForceCloseCallback ()
  48. {
  49. if (Application.Top.Running && FakeConsole.MockKeyPresses.Count == 0)
  50. {
  51. Application.RequestStop ();
  52. // See #2474 for why this is commented out
  53. Assert.Fail (
  54. $"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey} after {abortTime}ms. Force quit.");
  55. }
  56. return false;
  57. }
  58. //output.WriteLine ($" Add timeout to force quit after {abortTime}ms");
  59. _ = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  60. Application.Iteration += (s, a) =>
  61. {
  62. //output.WriteLine ($" iteration {++iterations}");
  63. if (Application.Top.Running && FakeConsole.MockKeyPresses.Count == 0)
  64. {
  65. Application.RequestStop ();
  66. Assert.Fail ($"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey}. Force quit.");
  67. }
  68. };
  69. scenario.Main ();
  70. scenario.Dispose ();
  71. Application.Shutdown ();
  72. #if DEBUG_IDISPOSABLE
  73. Assert.Empty (Responder.Instances);
  74. #endif
  75. }
  76. [Fact]
  77. public void Run_All_Views_Tester_Scenario ()
  78. {
  79. Window _leftPane;
  80. ListView _classListView;
  81. FrameView _hostPane;
  82. Dictionary<string, Type> _viewClasses;
  83. View _curView = null;
  84. // Settings
  85. FrameView _settingsPane;
  86. FrameView _locationFrame;
  87. RadioGroup _xRadioGroup;
  88. TextField _xText;
  89. var _xVal = 0;
  90. RadioGroup _yRadioGroup;
  91. TextField _yText;
  92. var _yVal = 0;
  93. FrameView _sizeFrame;
  94. RadioGroup _wRadioGroup;
  95. TextField _wText;
  96. var _wVal = 0;
  97. RadioGroup _hRadioGroup;
  98. TextField _hText;
  99. var _hVal = 0;
  100. List<string> posNames = new () { "Percent", "AnchorEnd", "Center", "Absolute" };
  101. List<string> dimNames = new () { "Auto", "Percent", "Fill", "Absolute" };
  102. Application.Init (new FakeDriver ());
  103. var top = new Toplevel ();
  104. _viewClasses = TestHelpers.GetAllViewClasses ().ToDictionary (t => t.Name);
  105. _leftPane = new ()
  106. {
  107. Title = "Classes",
  108. X = 0,
  109. Y = 0,
  110. Width = 15,
  111. Height = Dim.Fill (1), // for status bar
  112. CanFocus = false,
  113. ColorScheme = Colors.ColorSchemes ["TopLevel"]
  114. };
  115. _classListView = new ()
  116. {
  117. X = 0,
  118. Y = 0,
  119. Width = Dim.Fill (),
  120. Height = Dim.Fill (),
  121. AllowsMarking = false,
  122. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  123. Source = new ListWrapper (_viewClasses.Keys.ToList ())
  124. };
  125. _leftPane.Add (_classListView);
  126. _settingsPane = new ()
  127. {
  128. X = Pos.Right (_leftPane),
  129. Y = 0, // for menu
  130. Width = Dim.Fill (),
  131. Height = 10,
  132. CanFocus = false,
  133. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  134. Title = "Settings"
  135. };
  136. var radioItems = new [] { "Percent(x)", "AnchorEnd(x)", "Center", "Absolute(x)" };
  137. _locationFrame = new ()
  138. {
  139. X = 0,
  140. Y = 0,
  141. Height = 3 + radioItems.Length,
  142. Width = 36,
  143. Title = "Location (Pos)"
  144. };
  145. _settingsPane.Add (_locationFrame);
  146. var label = new Label { X = 0, Y = 0, Text = "x:" };
  147. _locationFrame.Add (label);
  148. _xRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  149. _xText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_xVal}" };
  150. _locationFrame.Add (_xText);
  151. _locationFrame.Add (_xRadioGroup);
  152. radioItems = new [] { "Percent(y)", "AnchorEnd(y)", "Center", "Absolute(y)" };
  153. label = new () { X = Pos.Right (_xRadioGroup) + 1, Y = 0, Text = "y:" };
  154. _locationFrame.Add (label);
  155. _yText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_yVal}" };
  156. _locationFrame.Add (_yText);
  157. _yRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  158. _locationFrame.Add (_yRadioGroup);
  159. _sizeFrame = new ()
  160. {
  161. X = Pos.Right (_locationFrame),
  162. Y = Pos.Y (_locationFrame),
  163. Height = 3 + radioItems.Length,
  164. Width = 40,
  165. Title = "Size (Dim)"
  166. };
  167. radioItems = new [] { "Auto()", "Percent(width)", "Fill(width)", "Absolute(width)" };
  168. label = new () { X = 0, Y = 0, Text = "width:" };
  169. _sizeFrame.Add (label);
  170. _wRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  171. _wText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_wVal}" };
  172. _sizeFrame.Add (_wText);
  173. _sizeFrame.Add (_wRadioGroup);
  174. radioItems = new [] { "Auto()", "Percent(height)", "Fill(height)", "Absolute(height)" };
  175. label = new () { X = Pos.Right (_wRadioGroup) + 1, Y = 0, Text = "height:" };
  176. _sizeFrame.Add (label);
  177. _hText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_hVal}" };
  178. _sizeFrame.Add (_hText);
  179. _hRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  180. _sizeFrame.Add (_hRadioGroup);
  181. _settingsPane.Add (_sizeFrame);
  182. _hostPane = new ()
  183. {
  184. X = Pos.Right (_leftPane),
  185. Y = Pos.Bottom (_settingsPane),
  186. Width = Dim.Fill (),
  187. Height = Dim.Fill (1), // + 1 for status bar
  188. ColorScheme = Colors.ColorSchemes ["Dialog"]
  189. };
  190. _classListView.OpenSelectedItem += (s, a) => { _settingsPane.SetFocus (); };
  191. _classListView.SelectedItemChanged += (s, args) =>
  192. {
  193. // Remove existing class, if any
  194. if (_curView != null)
  195. {
  196. _curView.LayoutComplete -= LayoutCompleteHandler;
  197. _hostPane.Remove (_curView);
  198. _curView.Dispose ();
  199. _curView = null;
  200. _hostPane.FillRect (_hostPane.Viewport);
  201. }
  202. _curView = CreateClass (_viewClasses.Values.ToArray () [_classListView.SelectedItem]);
  203. };
  204. _xRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  205. _xText.TextChanged += (s, args) =>
  206. {
  207. try
  208. {
  209. _xVal = int.Parse (_xText.Text);
  210. DimPosChanged (_curView);
  211. }
  212. catch
  213. { }
  214. };
  215. _yText.TextChanged += (s, e) =>
  216. {
  217. try
  218. {
  219. _yVal = int.Parse (_yText.Text);
  220. DimPosChanged (_curView);
  221. }
  222. catch
  223. { }
  224. };
  225. _yRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  226. _wRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  227. _wText.TextChanged += (s, args) =>
  228. {
  229. try
  230. {
  231. _wVal = int.Parse (_wText.Text);
  232. DimPosChanged (_curView);
  233. }
  234. catch
  235. { }
  236. };
  237. _hText.TextChanged += (s, args) =>
  238. {
  239. try
  240. {
  241. _hVal = int.Parse (_hText.Text);
  242. DimPosChanged (_curView);
  243. }
  244. catch
  245. { }
  246. };
  247. _hRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  248. top.Add (_leftPane, _settingsPane, _hostPane);
  249. top.LayoutSubviews ();
  250. _curView = CreateClass (_viewClasses.First ().Value);
  251. var iterations = 0;
  252. Application.Iteration += (s, a) =>
  253. {
  254. iterations++;
  255. if (iterations < _viewClasses.Count)
  256. {
  257. _classListView.MoveDown ();
  258. Assert.Equal (
  259. _curView.GetType ().Name,
  260. _viewClasses.Values.ToArray () [_classListView.SelectedItem].Name
  261. );
  262. }
  263. else
  264. {
  265. Application.RequestStop ();
  266. }
  267. };
  268. Application.Run (top);
  269. Assert.Equal (_viewClasses.Count, iterations);
  270. top.Dispose ();
  271. Application.Shutdown ();
  272. void DimPosChanged (View view)
  273. {
  274. if (view == null)
  275. {
  276. return;
  277. }
  278. try
  279. {
  280. switch (_xRadioGroup.SelectedItem)
  281. {
  282. case 0:
  283. view.X = Pos.Percent (_xVal);
  284. break;
  285. case 1:
  286. view.X = Pos.AnchorEnd (_xVal);
  287. break;
  288. case 2:
  289. view.X = Pos.Center ();
  290. break;
  291. case 3:
  292. view.X = Pos.Absolute (_xVal);
  293. break;
  294. }
  295. switch (_yRadioGroup.SelectedItem)
  296. {
  297. case 0:
  298. view.Y = Pos.Percent (_yVal);
  299. break;
  300. case 1:
  301. view.Y = Pos.AnchorEnd (_yVal);
  302. break;
  303. case 2:
  304. view.Y = Pos.Center ();
  305. break;
  306. case 3:
  307. view.Y = Pos.Absolute (_yVal);
  308. break;
  309. }
  310. switch (_wRadioGroup.SelectedItem)
  311. {
  312. case 0:
  313. view.Width = Dim.Percent (_wVal);
  314. break;
  315. case 1:
  316. view.Width = Dim.Fill (_wVal);
  317. break;
  318. case 2:
  319. view.Width = Dim.Absolute (_wVal);
  320. break;
  321. }
  322. switch (_hRadioGroup.SelectedItem)
  323. {
  324. case 0:
  325. view.Height = Dim.Percent (_hVal);
  326. break;
  327. case 1:
  328. view.Height = Dim.Fill (_hVal);
  329. break;
  330. case 2:
  331. view.Height = Dim.Absolute (_hVal);
  332. break;
  333. }
  334. }
  335. catch (Exception e)
  336. {
  337. MessageBox.ErrorQuery ("Exception", e.Message, "Ok");
  338. }
  339. UpdateTitle (view);
  340. }
  341. void UpdateSettings (View view)
  342. {
  343. var x = view.X.ToString ();
  344. var y = view.Y.ToString ();
  345. _xRadioGroup.SelectedItem = posNames.IndexOf (posNames.Where (s => x.Contains (s)).First ());
  346. _yRadioGroup.SelectedItem = posNames.IndexOf (posNames.Where (s => y.Contains (s)).First ());
  347. _xText.Text = $"{view.Frame.X}";
  348. _yText.Text = $"{view.Frame.Y}";
  349. var w = view.Width.ToString ();
  350. var h = view.Height.ToString ();
  351. _wRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.Where (s => w.Contains (s)).First ());
  352. _hRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.Where (s => h.Contains (s)).First ());
  353. _wText.Text = $"{view.Frame.Width}";
  354. _hText.Text = $"{view.Frame.Height}";
  355. }
  356. void UpdateTitle (View view) { _hostPane.Title = $"{view.GetType ().Name} - {view.X}, {view.Y}, {view.Width}, {view.Height}"; }
  357. View CreateClass (Type type)
  358. {
  359. // If we are to create a generic Type
  360. if (type.IsGenericType)
  361. {
  362. // For each of the <T> arguments
  363. List<Type> typeArguments = new ();
  364. // use <object>
  365. foreach (Type arg in type.GetGenericArguments ())
  366. {
  367. typeArguments.Add (typeof (object));
  368. }
  369. // And change what type we are instantiating from MyClass<T> to MyClass<object>
  370. type = type.MakeGenericType (typeArguments.ToArray ());
  371. }
  372. // Instantiate view
  373. var view = (View)Activator.CreateInstance (type);
  374. if (view is null)
  375. {
  376. return null;
  377. }
  378. if (view.Width is not DimAuto)
  379. {
  380. view.Width = Dim.Percent (75);
  381. }
  382. if (view.Height is not DimAuto)
  383. {
  384. view.Height = Dim.Percent (75);
  385. }
  386. // Set the colorscheme to make it stand out if is null by default
  387. view.ColorScheme ??= Colors.ColorSchemes ["Base"];
  388. // If the view supports a Text property, set it so we have something to look at
  389. if (view.GetType ().GetProperty ("Text") != null)
  390. {
  391. try
  392. {
  393. view.GetType ().GetProperty ("Text")?.GetSetMethod ()?.Invoke (view, new [] { "Test Text" });
  394. }
  395. catch (TargetInvocationException e)
  396. {
  397. MessageBox.ErrorQuery ("Exception", e.InnerException.Message, "Ok");
  398. view = null;
  399. }
  400. }
  401. // If the view supports a Title property, set it so we have something to look at
  402. if (view != null && view.GetType ().GetProperty ("Title") != null)
  403. {
  404. if (view.GetType ().GetProperty ("Title").PropertyType == typeof (string))
  405. {
  406. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  407. }
  408. else
  409. {
  410. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  411. }
  412. }
  413. // If the view supports a Source property, set it so we have something to look at
  414. if (view != null
  415. && view.GetType ().GetProperty ("Source") != null
  416. && view.GetType ().GetProperty ("Source").PropertyType == typeof (IListDataSource))
  417. {
  418. var source = new ListWrapper (new List<string> { "Test Text #1", "Test Text #2", "Test Text #3" });
  419. view?.GetType ().GetProperty ("Source")?.GetSetMethod ()?.Invoke (view, new [] { source });
  420. }
  421. // Add
  422. _hostPane.Add (view);
  423. //DimPosChanged ();
  424. _hostPane.LayoutSubviews ();
  425. _hostPane.Clear ();
  426. _hostPane.SetNeedsDisplay ();
  427. UpdateSettings (view);
  428. UpdateTitle (view);
  429. view.LayoutComplete += LayoutCompleteHandler;
  430. return view;
  431. }
  432. void LayoutCompleteHandler (object sender, LayoutEventArgs args) { UpdateTitle (_curView); }
  433. }
  434. [Fact]
  435. public void Run_Generic ()
  436. {
  437. List<Scenario> scenarios = Scenario.GetScenarios ();
  438. Assert.NotEmpty (scenarios);
  439. int item = scenarios.FindIndex (s => s.GetName ().Equals ("Generic", StringComparison.OrdinalIgnoreCase));
  440. Scenario generic = scenarios [item];
  441. Application.Init (new FakeDriver ());
  442. // BUGBUG: (#2474) For some reason ReadKey is not returning the QuitKey for some Scenarios
  443. // by adding this Space it seems to work.
  444. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  445. var ms = 100;
  446. var abortCount = 0;
  447. Func<bool> abortCallback = () =>
  448. {
  449. abortCount++;
  450. _output.WriteLine ($"'Generic' abortCount {abortCount}");
  451. Application.RequestStop ();
  452. return false;
  453. };
  454. var iterations = 0;
  455. object token = null;
  456. Application.Iteration += (s, a) =>
  457. {
  458. if (token == null)
  459. {
  460. // Timeout only must start at first iteration
  461. token = Application.MainLoop.AddTimeout (TimeSpan.FromMilliseconds (ms), abortCallback);
  462. }
  463. iterations++;
  464. _output.WriteLine ($"'Generic' iteration {iterations}");
  465. // Stop if we run out of control...
  466. if (iterations == 10)
  467. {
  468. _output.WriteLine ("'Generic' had to be force quit!");
  469. Application.RequestStop ();
  470. }
  471. };
  472. Application.KeyDown += (sender, args) =>
  473. {
  474. // See #2474 for why this is commented out
  475. Assert.Equal (KeyCode.CtrlMask | KeyCode.Q, args.KeyCode);
  476. };
  477. generic.Main ();
  478. Assert.Equal (0, abortCount);
  479. // # of key up events should match # of iterations
  480. Assert.Equal (1, iterations);
  481. generic.Dispose ();
  482. // Shutdown must be called to safely clean up Application if Init has been called
  483. Application.Shutdown ();
  484. #if DEBUG_IDISPOSABLE
  485. Assert.Empty (Responder.Instances);
  486. #endif
  487. }
  488. private int CreateInput (string input)
  489. {
  490. FakeConsole.MockKeyPresses.Clear ();
  491. // Put a QuitKey in at the end
  492. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  493. foreach (char c in input.Reverse ())
  494. {
  495. var key = KeyCode.Null;
  496. if (char.IsLetter (c))
  497. {
  498. key = (KeyCode)char.ToUpper (c) | (char.IsUpper (c) ? KeyCode.ShiftMask : 0);
  499. }
  500. else
  501. {
  502. key = (KeyCode)c;
  503. }
  504. FakeConsole.PushMockKeyPress (key);
  505. }
  506. return FakeConsole.MockKeyPresses.Count;
  507. }
  508. }