GuiTestContext.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. using System.Diagnostics;
  2. using System.Drawing;
  3. using System.Text;
  4. using Microsoft.Extensions.Logging;
  5. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  6. namespace TerminalGuiFluentTesting;
  7. /// <summary>
  8. /// Fluent API context for testing a Terminal.Gui application. Create
  9. /// an instance using <see cref="With"/> static class.
  10. /// </summary>
  11. public class GuiTestContext : IDisposable
  12. {
  13. private readonly CancellationTokenSource _cts = new ();
  14. private readonly CancellationTokenSource _hardStop;
  15. private readonly Task _runTask;
  16. private Exception? _ex;
  17. private readonly FakeOutput _output = new ();
  18. private readonly FakeWindowsInput _winInput;
  19. private readonly FakeNetInput _netInput;
  20. private View? _lastView;
  21. private readonly object _logsLock = new ();
  22. private readonly StringBuilder _logsSb;
  23. private readonly TestDriver _driver;
  24. private bool _finished;
  25. private readonly FakeSizeMonitor _fakeSizeMonitor;
  26. private readonly TimeSpan _timeout;
  27. internal GuiTestContext (Func<Toplevel> topLevelBuilder, int width, int height, TestDriver driver, TextWriter? logWriter = null, TimeSpan? timeout = null)
  28. {
  29. _timeout = timeout ?? TimeSpan.FromSeconds (30);
  30. _hardStop = new (_timeout);
  31. // Remove frame limit
  32. Application.MaximumIterationsPerSecond = ushort.MaxValue;
  33. IApplication origApp = ApplicationImpl.Instance;
  34. ILogger? origLogger = Logging.Logger;
  35. _logsSb = new ();
  36. _driver = driver;
  37. _netInput = new (_cts.Token);
  38. _winInput = new (_cts.Token);
  39. _output.Size = new (width, height);
  40. _fakeSizeMonitor = new ();
  41. IComponentFactory cf = driver == TestDriver.DotNet
  42. ? new FakeNetComponentFactory (_netInput, _output, _fakeSizeMonitor)
  43. : (IComponentFactory)new FakeWindowsComponentFactory (_winInput, _output, _fakeSizeMonitor);
  44. var impl = new ApplicationImpl (cf);
  45. var booting = new SemaphoreSlim (0, 1);
  46. // Start the application in a background thread
  47. _runTask = Task.Run (
  48. () =>
  49. {
  50. try
  51. {
  52. ApplicationImpl.ChangeInstance (impl);
  53. ILogger logger = LoggerFactory.Create (
  54. builder =>
  55. builder.SetMinimumLevel (LogLevel.Trace)
  56. .AddProvider (
  57. new TextWriterLoggerProvider (
  58. new ThreadSafeStringWriter (_logsSb, _logsLock))))
  59. .CreateLogger ("Test Logging");
  60. Logging.Logger = logger;
  61. impl.Init (null, GetDriverName ());
  62. booting.Release ();
  63. Toplevel t = topLevelBuilder ();
  64. t.Closed += (s, e) => { _finished = true; };
  65. Application.Run (t); // This will block, but it's on a background thread now
  66. t.Dispose ();
  67. Application.Shutdown ();
  68. _cts.Cancel ();
  69. }
  70. catch (OperationCanceledException)
  71. { }
  72. catch (Exception ex)
  73. {
  74. _ex = ex;
  75. if (logWriter != null)
  76. {
  77. WriteOutLogs (logWriter);
  78. }
  79. _hardStop.Cancel ();
  80. }
  81. finally
  82. {
  83. ApplicationImpl.ChangeInstance (origApp);
  84. Logging.Logger = origLogger;
  85. _finished = true;
  86. Application.MaximumIterationsPerSecond = Application.DEFAULT_MAXIMUM_ITERATIONS_PER_SECOND;
  87. }
  88. },
  89. _cts.Token);
  90. // Wait for booting to complete with a timeout to avoid hangs
  91. if (!booting.WaitAsync (_timeout).Result)
  92. {
  93. throw new TimeoutException ("Application failed to start within the allotted time.");
  94. }
  95. ResizeConsole (width, height);
  96. if (_ex != null)
  97. {
  98. throw new ("Application crashed", _ex);
  99. }
  100. }
  101. private string GetDriverName ()
  102. {
  103. return _driver switch
  104. {
  105. TestDriver.Windows => "windows",
  106. TestDriver.DotNet => "dotnet",
  107. _ =>
  108. throw new ArgumentOutOfRangeException ()
  109. };
  110. }
  111. /// <summary>
  112. /// Stops the application and waits for the background thread to exit.
  113. /// </summary>
  114. public GuiTestContext Stop ()
  115. {
  116. if (_runTask.IsCompleted)
  117. {
  118. return this;
  119. }
  120. WaitIteration (() => { Application.RequestStop (); });
  121. // Wait for the application to stop, but give it a 1-second timeout
  122. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  123. {
  124. _cts.Cancel ();
  125. // Timeout occurred, force the task to stop
  126. _hardStop.Cancel ();
  127. // App is having trouble shutting down, try sending some more shutdown stuff from this thread.
  128. // If this doesn't work there will be test cascade failures as the main loop continues to run during next test.
  129. try
  130. {
  131. Application.RequestStop ();
  132. Application.Shutdown ();
  133. }
  134. catch (Exception)
  135. {
  136. throw new TimeoutException ("Application failed to stop within the allotted time.", _ex);
  137. }
  138. throw new TimeoutException ("Application failed to stop within the allotted time.", _ex);
  139. }
  140. _cts.Cancel ();
  141. if (_ex != null)
  142. {
  143. throw _ex; // Propagate any exception that happened in the background task
  144. }
  145. return this;
  146. }
  147. /// <summary>
  148. /// Hard stops the application and waits for the background thread to exit.
  149. /// </summary>
  150. public void HardStop (Exception? ex = null)
  151. {
  152. if (ex != null)
  153. {
  154. _ex = ex;
  155. }
  156. _hardStop.Cancel ();
  157. Stop ();
  158. }
  159. /// <summary>
  160. /// Cleanup to avoid state bleed between tests
  161. /// </summary>
  162. public void Dispose ()
  163. {
  164. Stop ();
  165. if (_hardStop.IsCancellationRequested)
  166. {
  167. throw new (
  168. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test",
  169. _ex);
  170. }
  171. _hardStop.Cancel ();
  172. }
  173. /// <summary>
  174. /// Adds the given <paramref name="v"/> to the current top level view
  175. /// and performs layout.
  176. /// </summary>
  177. /// <param name="v"></param>
  178. /// <returns></returns>
  179. public GuiTestContext Add (View v)
  180. {
  181. WaitIteration (
  182. () =>
  183. {
  184. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  185. top.Add (v);
  186. top.Layout ();
  187. _lastView = v;
  188. });
  189. return this;
  190. }
  191. /// <summary>
  192. /// Simulates changing the console size e.g. by resizing window in your operating system
  193. /// </summary>
  194. /// <param name="width">new Width for the console.</param>
  195. /// <param name="height">new Height for the console.</param>
  196. /// <returns></returns>
  197. public GuiTestContext ResizeConsole (int width, int height)
  198. {
  199. return WaitIteration (
  200. () =>
  201. {
  202. _output.Size = new (width, height);
  203. _fakeSizeMonitor.RaiseSizeChanging (_output.Size);
  204. var d = (IConsoleDriverFacade)Application.Driver!;
  205. d.OutputBuffer.SetWindowSize (width, height);
  206. });
  207. }
  208. public GuiTestContext ScreenShot (string title, TextWriter writer)
  209. {
  210. return WaitIteration (
  211. () =>
  212. {
  213. writer.WriteLine (title + ":");
  214. var text = Application.ToString ();
  215. writer.WriteLine (text);
  216. });
  217. }
  218. /// <summary>
  219. /// Writes all Terminal.Gui engine logs collected so far to the <paramref name="writer"/>
  220. /// </summary>
  221. /// <param name="writer"></param>
  222. /// <returns></returns>
  223. public GuiTestContext WriteOutLogs (TextWriter writer)
  224. {
  225. lock (_logsLock)
  226. {
  227. writer.WriteLine (_logsSb.ToString ());
  228. }
  229. return this; //WaitIteration();
  230. }
  231. /// <summary>
  232. /// Waits until the end of the current iteration of the main loop. Optionally
  233. /// running a given <paramref name="a"/> action on the UI thread at that time.
  234. /// </summary>
  235. /// <param name="a"></param>
  236. /// <returns></returns>
  237. public GuiTestContext WaitIteration (Action? a = null)
  238. {
  239. // If application has already exited don't wait!
  240. if (_finished || _cts.Token.IsCancellationRequested || _hardStop.Token.IsCancellationRequested)
  241. {
  242. return this;
  243. }
  244. if (Thread.CurrentThread.ManagedThreadId == Application.MainThreadId)
  245. {
  246. throw new NotSupportedException ("Cannot WaitIteration during Invoke");
  247. }
  248. a ??= () => { };
  249. var ctsLocal = new CancellationTokenSource ();
  250. Application.Invoke (
  251. () =>
  252. {
  253. try
  254. {
  255. a ();
  256. ctsLocal.Cancel ();
  257. }
  258. catch (Exception e)
  259. {
  260. _ex = e;
  261. _hardStop.Cancel ();
  262. }
  263. });
  264. // Blocks until either the token or the hardStopToken is cancelled.
  265. WaitHandle.WaitAny (
  266. new []
  267. {
  268. _cts.Token.WaitHandle,
  269. _hardStop.Token.WaitHandle,
  270. ctsLocal.Token.WaitHandle
  271. });
  272. return this;
  273. }
  274. /// <summary>
  275. /// Performs the supplied <paramref name="doAction"/> immediately.
  276. /// Enables running commands without breaking the Fluent API calls.
  277. /// </summary>
  278. /// <param name="doAction"></param>
  279. /// <returns></returns>
  280. public GuiTestContext Then (Action doAction)
  281. {
  282. try
  283. {
  284. WaitIteration (doAction);
  285. }
  286. catch (Exception ex)
  287. {
  288. _ex = ex;
  289. HardStop ();
  290. throw;
  291. }
  292. return this;
  293. }
  294. /// <summary>
  295. /// Simulates a right click at the given screen coordinates on the current driver.
  296. /// This is a raw input event that goes through entire processing pipeline as though
  297. /// user had pressed the mouse button physically.
  298. /// </summary>
  299. /// <param name="screenX">0 indexed screen coordinates</param>
  300. /// <param name="screenY">0 indexed screen coordinates</param>
  301. /// <returns></returns>
  302. public GuiTestContext RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  303. /// <summary>
  304. /// Simulates a left click at the given screen coordinates on the current driver.
  305. /// This is a raw input event that goes through entire processing pipeline as though
  306. /// user had pressed the mouse button physically.
  307. /// </summary>
  308. /// <param name="screenX">0 indexed screen coordinates</param>
  309. /// <param name="screenY">0 indexed screen coordinates</param>
  310. /// <returns></returns>
  311. public GuiTestContext LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  312. public GuiTestContext LeftClick<T> (Func<T, bool> evaluator) where T : View { return Click (WindowsConsole.ButtonState.Button1Pressed, evaluator); }
  313. private GuiTestContext Click<T> (WindowsConsole.ButtonState btn, Func<T, bool> evaluator) where T : View
  314. {
  315. T v;
  316. var screen = Point.Empty;
  317. GuiTestContext ctx = WaitIteration (
  318. () =>
  319. {
  320. v = Find (evaluator);
  321. screen = v.ViewportToScreen (new Point (0, 0));
  322. });
  323. Click (btn, screen.X, screen.Y);
  324. return ctx;
  325. }
  326. private GuiTestContext Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  327. {
  328. switch (_driver)
  329. {
  330. case TestDriver.Windows:
  331. _winInput.InputBuffer!.Enqueue (
  332. new ()
  333. {
  334. EventType = WindowsConsole.EventType.Mouse,
  335. MouseEvent = new ()
  336. {
  337. ButtonState = btn,
  338. MousePosition = new ((short)screenX, (short)screenY)
  339. }
  340. });
  341. _winInput.InputBuffer.Enqueue (
  342. new ()
  343. {
  344. EventType = WindowsConsole.EventType.Mouse,
  345. MouseEvent = new ()
  346. {
  347. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  348. MousePosition = new ((short)screenX, (short)screenY)
  349. }
  350. });
  351. return WaitUntil (() => _winInput.InputBuffer.IsEmpty);
  352. case TestDriver.DotNet:
  353. int netButton = btn switch
  354. {
  355. WindowsConsole.ButtonState.Button1Pressed => 0,
  356. WindowsConsole.ButtonState.Button2Pressed => 1,
  357. WindowsConsole.ButtonState.Button3Pressed => 2,
  358. WindowsConsole.ButtonState.RightmostButtonPressed => 2,
  359. _ => throw new ArgumentOutOfRangeException (nameof (btn))
  360. };
  361. foreach (ConsoleKeyInfo k in NetSequences.Click (netButton, screenX, screenY))
  362. {
  363. SendNetKey (k, false);
  364. }
  365. return WaitIteration ();
  366. default:
  367. throw new ArgumentOutOfRangeException ();
  368. }
  369. }
  370. private GuiTestContext WaitUntil (Func<bool> condition)
  371. {
  372. GuiTestContext? c = null;
  373. var sw = Stopwatch.StartNew ();
  374. while (!condition ())
  375. {
  376. if (sw.Elapsed > _timeout)
  377. {
  378. throw new TimeoutException ("Failed to reach condition within the time limit");
  379. }
  380. c = WaitIteration ();
  381. }
  382. return c ?? this;
  383. }
  384. public GuiTestContext Down ()
  385. {
  386. switch (_driver)
  387. {
  388. case TestDriver.Windows:
  389. SendWindowsKey (ConsoleKeyMapping.VK.DOWN);
  390. break;
  391. case TestDriver.DotNet:
  392. foreach (ConsoleKeyInfo k in NetSequences.Down)
  393. {
  394. SendNetKey (k);
  395. }
  396. break;
  397. default:
  398. throw new ArgumentOutOfRangeException ();
  399. }
  400. return WaitIteration ();
  401. }
  402. /// <summary>
  403. /// Simulates the Right cursor key
  404. /// </summary>
  405. /// <returns></returns>
  406. /// <exception cref="ArgumentOutOfRangeException"></exception>
  407. public GuiTestContext Right ()
  408. {
  409. switch (_driver)
  410. {
  411. case TestDriver.Windows:
  412. SendWindowsKey (ConsoleKeyMapping.VK.RIGHT);
  413. break;
  414. case TestDriver.DotNet:
  415. foreach (ConsoleKeyInfo k in NetSequences.Right)
  416. {
  417. SendNetKey (k);
  418. }
  419. WaitIteration ();
  420. break;
  421. default:
  422. throw new ArgumentOutOfRangeException ();
  423. }
  424. return WaitIteration ();
  425. }
  426. /// <summary>
  427. /// Simulates the Left cursor key
  428. /// </summary>
  429. /// <returns></returns>
  430. /// <exception cref="ArgumentOutOfRangeException"></exception>
  431. public GuiTestContext Left ()
  432. {
  433. switch (_driver)
  434. {
  435. case TestDriver.Windows:
  436. SendWindowsKey (ConsoleKeyMapping.VK.LEFT);
  437. break;
  438. case TestDriver.DotNet:
  439. foreach (ConsoleKeyInfo k in NetSequences.Left)
  440. {
  441. SendNetKey (k);
  442. }
  443. break;
  444. default:
  445. throw new ArgumentOutOfRangeException ();
  446. }
  447. return WaitIteration ();
  448. }
  449. /// <summary>
  450. /// Simulates the up cursor key
  451. /// </summary>
  452. /// <returns></returns>
  453. /// <exception cref="ArgumentOutOfRangeException"></exception>
  454. public GuiTestContext Up ()
  455. {
  456. switch (_driver)
  457. {
  458. case TestDriver.Windows:
  459. SendWindowsKey (ConsoleKeyMapping.VK.UP);
  460. break;
  461. case TestDriver.DotNet:
  462. foreach (ConsoleKeyInfo k in NetSequences.Up)
  463. {
  464. SendNetKey (k);
  465. }
  466. break;
  467. default:
  468. throw new ArgumentOutOfRangeException ();
  469. }
  470. return WaitIteration ();
  471. }
  472. /// <summary>
  473. /// Simulates pressing the Return/Enter (newline) key.
  474. /// </summary>
  475. /// <returns></returns>
  476. /// <exception cref="ArgumentOutOfRangeException"></exception>
  477. public GuiTestContext Enter ()
  478. {
  479. switch (_driver)
  480. {
  481. case TestDriver.Windows:
  482. SendWindowsKey (
  483. new WindowsConsole.KeyEventRecord
  484. {
  485. UnicodeChar = '\r',
  486. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  487. wRepeatCount = 1,
  488. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  489. wVirtualScanCode = 28
  490. });
  491. break;
  492. case TestDriver.DotNet:
  493. SendNetKey (new ('\r', ConsoleKey.Enter, false, false, false));
  494. break;
  495. default:
  496. throw new ArgumentOutOfRangeException ();
  497. }
  498. return WaitIteration ();
  499. }
  500. /// <summary>
  501. /// Simulates pressing the Esc (Escape) key.
  502. /// </summary>
  503. /// <returns></returns>
  504. /// <exception cref="ArgumentOutOfRangeException"></exception>
  505. public GuiTestContext Escape ()
  506. {
  507. switch (_driver)
  508. {
  509. case TestDriver.Windows:
  510. SendWindowsKey (
  511. new WindowsConsole.KeyEventRecord
  512. {
  513. UnicodeChar = '\u001b',
  514. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  515. wRepeatCount = 1,
  516. wVirtualKeyCode = ConsoleKeyMapping.VK.ESCAPE,
  517. wVirtualScanCode = 1
  518. });
  519. break;
  520. case TestDriver.DotNet:
  521. // Note that this accurately describes how Esc comes in. Typically, ConsoleKey is None
  522. // even though you would think it would be Escape - it isn't
  523. SendNetKey (new ('\u001b', ConsoleKey.None, false, false, false));
  524. break;
  525. default:
  526. throw new ArgumentOutOfRangeException ();
  527. }
  528. return this;
  529. }
  530. /// <summary>
  531. /// Simulates pressing the Tab key.
  532. /// </summary>
  533. /// <returns></returns>
  534. /// <exception cref="ArgumentOutOfRangeException"></exception>
  535. public GuiTestContext Tab ()
  536. {
  537. switch (_driver)
  538. {
  539. case TestDriver.Windows:
  540. SendWindowsKey (
  541. new WindowsConsole.KeyEventRecord
  542. {
  543. UnicodeChar = '\t',
  544. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  545. wRepeatCount = 1,
  546. wVirtualKeyCode = 0,
  547. wVirtualScanCode = 0
  548. });
  549. break;
  550. case TestDriver.DotNet:
  551. // Note that this accurately describes how Tab comes in. Typically, ConsoleKey is None
  552. // even though you would think it would be Tab - it isn't
  553. SendNetKey (new ('\t', ConsoleKey.None, false, false, false));
  554. break;
  555. default:
  556. throw new ArgumentOutOfRangeException ();
  557. }
  558. return this;
  559. }
  560. /// <summary>
  561. /// Registers a right click handler on the <see cref="LastView"/> added view (or root view) that
  562. /// will open the supplied <paramref name="contextMenu"/>.
  563. /// </summary>
  564. /// <param name="contextMenu"></param>
  565. /// <returns></returns>
  566. public GuiTestContext WithContextMenu (PopoverMenu? contextMenu)
  567. {
  568. LastView.MouseEvent += (s, e) =>
  569. {
  570. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  571. {
  572. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  573. // and the context menu is disposed when it is closed.
  574. Application.Popover?.Register (contextMenu);
  575. contextMenu?.MakeVisible (e.ScreenPosition);
  576. }
  577. };
  578. return this;
  579. }
  580. /// <summary>
  581. /// The last view added (e.g. with <see cref="Add"/>) or the root/current top.
  582. /// </summary>
  583. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  584. /// <summary>
  585. /// Send a full windows OS key including both down and up.
  586. /// </summary>
  587. /// <param name="fullKey"></param>
  588. private void SendWindowsKey (WindowsConsole.KeyEventRecord fullKey)
  589. {
  590. WindowsConsole.KeyEventRecord down = fullKey;
  591. WindowsConsole.KeyEventRecord up = fullKey; // because struct this is new copy
  592. down.bKeyDown = true;
  593. up.bKeyDown = false;
  594. _winInput.InputBuffer!.Enqueue (
  595. new ()
  596. {
  597. EventType = WindowsConsole.EventType.Key,
  598. KeyEvent = down
  599. });
  600. _winInput.InputBuffer.Enqueue (
  601. new ()
  602. {
  603. EventType = WindowsConsole.EventType.Key,
  604. KeyEvent = up
  605. });
  606. WaitIteration ();
  607. }
  608. private void SendNetKey (ConsoleKeyInfo consoleKeyInfo, bool wait = true)
  609. {
  610. _netInput.InputBuffer!.Enqueue (consoleKeyInfo);
  611. if (wait)
  612. {
  613. WaitUntil (() => _netInput.InputBuffer.IsEmpty);
  614. }
  615. }
  616. /// <summary>
  617. /// Sends a special key e.g. cursor key that does not map to a specific character
  618. /// </summary>
  619. /// <param name="specialKey"></param>
  620. private void SendWindowsKey (ConsoleKeyMapping.VK specialKey)
  621. {
  622. _winInput.InputBuffer!.Enqueue (
  623. new ()
  624. {
  625. EventType = WindowsConsole.EventType.Key,
  626. KeyEvent = new ()
  627. {
  628. bKeyDown = true,
  629. wRepeatCount = 0,
  630. wVirtualKeyCode = specialKey,
  631. wVirtualScanCode = 0,
  632. UnicodeChar = '\0',
  633. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  634. }
  635. });
  636. _winInput.InputBuffer.Enqueue (
  637. new ()
  638. {
  639. EventType = WindowsConsole.EventType.Key,
  640. KeyEvent = new ()
  641. {
  642. bKeyDown = false,
  643. wRepeatCount = 0,
  644. wVirtualKeyCode = specialKey,
  645. wVirtualScanCode = 0,
  646. UnicodeChar = '\0',
  647. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  648. }
  649. });
  650. WaitIteration ();
  651. }
  652. /// <summary>
  653. /// Sends a key to the application. This goes directly to Application and does not go through
  654. /// a driver.
  655. /// </summary>
  656. /// <param name="key"></param>
  657. /// <returns></returns>
  658. public GuiTestContext RaiseKeyDownEvent (Key key)
  659. {
  660. WaitIteration (() => Application.RaiseKeyDownEvent (key));
  661. return this; //WaitIteration();
  662. }
  663. /// <summary>
  664. /// Sets the input focus to the given <see cref="View"/>.
  665. /// Throws <see cref="ArgumentException"/> if focus did not change due to system
  666. /// constraints e.g. <paramref name="toFocus"/>
  667. /// <see cref="View.CanFocus"/> is <see langword="false"/>
  668. /// </summary>
  669. /// <param name="toFocus"></param>
  670. /// <returns></returns>
  671. /// <exception cref="ArgumentException"></exception>
  672. public GuiTestContext Focus (View toFocus)
  673. {
  674. toFocus.FocusDeepest (NavigationDirection.Forward, TabBehavior.TabStop);
  675. if (!toFocus.HasFocus)
  676. {
  677. throw new ArgumentException ("Failed to set focus, FocusDeepest did not result in HasFocus becoming true. Ensure view is added and focusable");
  678. }
  679. return WaitIteration ();
  680. }
  681. /// <summary>
  682. /// Tabs through the UI until a View matching the <paramref name="evaluator"/>
  683. /// is found (of Type T) or all views are looped through (back to the beginning)
  684. /// in which case triggers hard stop and Exception
  685. /// </summary>
  686. /// <param name="evaluator">
  687. /// Delegate that returns true if the passed View is the one
  688. /// you are trying to focus. Leave <see langword="null"/> to focus the first view of type
  689. /// <typeparamref name="T"/>
  690. /// </param>
  691. /// <returns></returns>
  692. /// <exception cref="ArgumentException"></exception>
  693. public GuiTestContext Focus<T> (Func<T, bool>? evaluator = null) where T : View
  694. {
  695. evaluator ??= _ => true;
  696. Toplevel? t = Application.Top;
  697. HashSet<View> seen = new ();
  698. if (t == null)
  699. {
  700. Fail ("Application.Top was null when trying to set focus");
  701. return this;
  702. }
  703. do
  704. {
  705. View? next = t.MostFocused;
  706. // Is view found?
  707. if (next is T v && evaluator (v))
  708. {
  709. return this;
  710. }
  711. // No, try tab to the next (or first)
  712. Tab ();
  713. WaitIteration ();
  714. next = t.MostFocused;
  715. if (next is null)
  716. {
  717. Fail (
  718. "Failed to tab to a view which matched the Type and evaluator constraints of the test because MostFocused became or was always null"
  719. + DescribeSeenViews (seen));
  720. return this;
  721. }
  722. // Track the views we have seen
  723. // We have looped around to the start again if it was already there
  724. if (!seen.Add (next))
  725. {
  726. Fail (
  727. "Failed to tab to a view which matched the Type and evaluator constraints of the test before looping back to the original View"
  728. + DescribeSeenViews (seen));
  729. return this;
  730. }
  731. }
  732. while (true);
  733. }
  734. private string DescribeSeenViews (HashSet<View> seen) { return Environment.NewLine + string.Join (Environment.NewLine, seen); }
  735. private T Find<T> (Func<T, bool> evaluator) where T : View
  736. {
  737. Toplevel? t = Application.Top;
  738. if (t == null)
  739. {
  740. Fail ("Application.Top was null when attempting to find view");
  741. }
  742. T? f = FindRecursive (t!, evaluator);
  743. if (f == null)
  744. {
  745. Fail ("Failed to tab to a view which matched the Type and evaluator constraints in any SubViews of top");
  746. }
  747. return f!;
  748. }
  749. private T? FindRecursive<T> (View current, Func<T, bool> evaluator) where T : View
  750. {
  751. foreach (View subview in current.SubViews)
  752. {
  753. if (subview is T match && evaluator (match))
  754. {
  755. return match;
  756. }
  757. // Recursive call
  758. T? result = FindRecursive (subview, evaluator);
  759. if (result != null)
  760. {
  761. return result;
  762. }
  763. }
  764. return null;
  765. }
  766. private void Fail (string reason)
  767. {
  768. Stop ();
  769. throw new (reason);
  770. }
  771. public GuiTestContext Send (Key key)
  772. {
  773. return WaitIteration (
  774. () =>
  775. {
  776. if (Application.Driver is IConsoleDriverFacade facade)
  777. {
  778. facade.InputProcessor.OnKeyDown (key);
  779. facade.InputProcessor.OnKeyUp (key);
  780. }
  781. else
  782. {
  783. Fail ("Expected Application.Driver to be IConsoleDriverFacade");
  784. }
  785. });
  786. }
  787. /// <summary>
  788. /// Returns the last set position of the cursor.
  789. /// </summary>
  790. /// <returns></returns>
  791. public Point GetCursorPosition () { return _output.CursorPosition; }
  792. }
  793. internal class FakeWindowsComponentFactory : WindowsComponentFactory
  794. {
  795. private readonly FakeWindowsInput _winInput;
  796. private readonly FakeOutput _output;
  797. private readonly FakeSizeMonitor _fakeSizeMonitor;
  798. public FakeWindowsComponentFactory (FakeWindowsInput winInput, FakeOutput output, FakeSizeMonitor fakeSizeMonitor)
  799. {
  800. _winInput = winInput;
  801. _output = output;
  802. _fakeSizeMonitor = fakeSizeMonitor;
  803. }
  804. /// <inheritdoc/>
  805. public override IConsoleInput<WindowsConsole.InputRecord> CreateInput () { return _winInput; }
  806. /// <inheritdoc/>
  807. public override IConsoleOutput CreateOutput () { return _output; }
  808. /// <inheritdoc/>
  809. public override IWindowSizeMonitor CreateWindowSizeMonitor (IConsoleOutput consoleOutput, IOutputBuffer outputBuffer) { return _fakeSizeMonitor; }
  810. }
  811. internal class FakeNetComponentFactory : NetComponentFactory
  812. {
  813. private readonly FakeNetInput _netInput;
  814. private readonly FakeOutput _output;
  815. private readonly FakeSizeMonitor _fakeSizeMonitor;
  816. public FakeNetComponentFactory (FakeNetInput netInput, FakeOutput output, FakeSizeMonitor fakeSizeMonitor)
  817. {
  818. _netInput = netInput;
  819. _output = output;
  820. _fakeSizeMonitor = fakeSizeMonitor;
  821. }
  822. /// <inheritdoc/>
  823. public override IConsoleInput<ConsoleKeyInfo> CreateInput () { return _netInput; }
  824. /// <inheritdoc/>
  825. public override IConsoleOutput CreateOutput () { return _output; }
  826. /// <inheritdoc/>
  827. public override IWindowSizeMonitor CreateWindowSizeMonitor (IConsoleOutput consoleOutput, IOutputBuffer outputBuffer) { return _fakeSizeMonitor; }
  828. }