ScenarioTests.cs 17 KB

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