ScenarioTests.cs 16 KB

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