ScenarioTests.cs 17 KB

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