ScenarioTests.cs 17 KB

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