ScenarioTests.cs 22 KB

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