ScenarioTests.cs 16 KB

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