ScenarioTests.cs 16 KB

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