ScenarioTests.cs 16 KB

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