ScenarioTests.cs 17 KB

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