ScenarioTests.cs 17 KB

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