ScenarioTests.cs 16 KB

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