GuiTestContext.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using System.Text;
  2. using Microsoft.Extensions.Logging;
  3. using Terminal.Gui;
  4. using Terminal.Gui.ConsoleDrivers;
  5. namespace TerminalGuiFluentTesting;
  6. /// <summary>
  7. /// Fluent API context for testing a Terminal.Gui application. Create
  8. /// an instance using <see cref="With"/> static class.
  9. /// </summary>
  10. public class GuiTestContext : IDisposable
  11. {
  12. private readonly CancellationTokenSource _cts = new ();
  13. private readonly CancellationTokenSource _hardStop = new (With.Timeout);
  14. private readonly Task _runTask;
  15. private Exception _ex;
  16. private readonly FakeOutput _output = new ();
  17. private readonly FakeWindowsInput _winInput;
  18. private readonly FakeNetInput _netInput;
  19. private View? _lastView;
  20. private readonly StringBuilder _logsSb;
  21. private readonly V2TestDriver _driver;
  22. internal GuiTestContext (Func<Toplevel> topLevelBuilder, int width, int height, V2TestDriver driver)
  23. {
  24. IApplication origApp = ApplicationImpl.Instance;
  25. ILogger? origLogger = Logging.Logger;
  26. _logsSb = new ();
  27. _driver = driver;
  28. _netInput = new (_cts.Token);
  29. _winInput = new (_cts.Token);
  30. _output.Size = new (width, height);
  31. var v2 = new ApplicationV2 (
  32. () => _netInput,
  33. () => _output,
  34. () => _winInput,
  35. () => _output);
  36. var booting = new SemaphoreSlim (0, 1);
  37. // Start the application in a background thread
  38. _runTask = Task.Run (
  39. () =>
  40. {
  41. try
  42. {
  43. ApplicationImpl.ChangeInstance (v2);
  44. ILogger logger = LoggerFactory.Create (
  45. builder =>
  46. builder.SetMinimumLevel (LogLevel.Trace)
  47. .AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb))))
  48. .CreateLogger ("Test Logging");
  49. Logging.Logger = logger;
  50. v2.Init (null, GetDriverName());
  51. booting.Release ();
  52. Toplevel t = topLevelBuilder ();
  53. Application.Run (t); // This will block, but it's on a background thread now
  54. Application.Shutdown ();
  55. }
  56. catch (OperationCanceledException)
  57. { }
  58. catch (Exception ex)
  59. {
  60. _ex = ex;
  61. }
  62. finally
  63. {
  64. ApplicationImpl.ChangeInstance (origApp);
  65. Logging.Logger = origLogger;
  66. }
  67. },
  68. _cts.Token);
  69. // Wait for booting to complete with a timeout to avoid hangs
  70. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  71. {
  72. throw new TimeoutException ("Application failed to start within the allotted time.");
  73. }
  74. WaitIteration ();
  75. }
  76. private string GetDriverName ()
  77. {
  78. return _driver switch
  79. {
  80. V2TestDriver.V2Win => "v2win",
  81. V2TestDriver.V2Net => "v2net",
  82. _ =>
  83. throw new ArgumentOutOfRangeException ()
  84. };
  85. }
  86. /// <summary>
  87. /// Stops the application and waits for the background thread to exit.
  88. /// </summary>
  89. public GuiTestContext Stop ()
  90. {
  91. if (_runTask.IsCompleted)
  92. {
  93. return this;
  94. }
  95. Application.Invoke (() => Application.RequestStop ());
  96. // Wait for the application to stop, but give it a 1-second timeout
  97. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  98. {
  99. _cts.Cancel ();
  100. // Timeout occurred, force the task to stop
  101. _hardStop.Cancel ();
  102. throw new TimeoutException ("Application failed to stop within the allotted time.");
  103. }
  104. _cts.Cancel ();
  105. if (_ex != null)
  106. {
  107. throw _ex; // Propagate any exception that happened in the background task
  108. }
  109. return this;
  110. }
  111. /// <summary>
  112. /// Cleanup to avoid state bleed between tests
  113. /// </summary>
  114. public void Dispose ()
  115. {
  116. Stop ();
  117. if (_hardStop.IsCancellationRequested)
  118. {
  119. throw new (
  120. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  121. }
  122. _hardStop.Cancel ();
  123. }
  124. /// <summary>
  125. /// Adds the given <paramref name="v"/> to the current top level view
  126. /// and performs layout.
  127. /// </summary>
  128. /// <param name="v"></param>
  129. /// <returns></returns>
  130. public GuiTestContext Add (View v)
  131. {
  132. WaitIteration (
  133. () =>
  134. {
  135. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  136. top.Add (v);
  137. top.Layout ();
  138. _lastView = v;
  139. });
  140. return this;
  141. }
  142. /// <summary>
  143. /// Simulates changing the console size e.g. by resizing window in your operating system
  144. /// </summary>
  145. /// <param name="width">new Width for the console.</param>
  146. /// <param name="height">new Height for the console.</param>
  147. /// <returns></returns>
  148. public GuiTestContext ResizeConsole (int width, int height)
  149. {
  150. _output.Size = new (width, height);
  151. return WaitIteration ();
  152. }
  153. public GuiTestContext ScreenShot (string title, TextWriter writer)
  154. {
  155. writer.WriteLine (title + ":");
  156. var text = Application.ToString ();
  157. writer.WriteLine (text);
  158. return WaitIteration ();
  159. }
  160. /// <summary>
  161. /// Writes all Terminal.Gui engine logs collected so far to the <paramref name="writer"/>
  162. /// </summary>
  163. /// <param name="writer"></param>
  164. /// <returns></returns>
  165. public GuiTestContext WriteOutLogs (TextWriter writer)
  166. {
  167. writer.WriteLine (_logsSb.ToString ());
  168. return WaitIteration ();
  169. }
  170. /// <summary>
  171. /// Waits until the end of the current iteration of the main loop. Optionally
  172. /// running a given <paramref name="a"/> action on the UI thread at that time.
  173. /// </summary>
  174. /// <param name="a"></param>
  175. /// <returns></returns>
  176. public GuiTestContext WaitIteration (Action? a = null)
  177. {
  178. a ??= () => { };
  179. var ctsLocal = new CancellationTokenSource ();
  180. Application.Invoke (
  181. () =>
  182. {
  183. a ();
  184. ctsLocal.Cancel ();
  185. });
  186. // Blocks until either the token or the hardStopToken is cancelled.
  187. WaitHandle.WaitAny (
  188. new []
  189. {
  190. _cts.Token.WaitHandle,
  191. _hardStop.Token.WaitHandle,
  192. ctsLocal.Token.WaitHandle
  193. });
  194. return this;
  195. }
  196. /// <summary>
  197. /// Performs the supplied <paramref name="doAction"/> immediately.
  198. /// Enables running commands without breaking the Fluent API calls.
  199. /// </summary>
  200. /// <param name="doAction"></param>
  201. /// <returns></returns>
  202. public GuiTestContext Then (Action doAction)
  203. {
  204. doAction ();
  205. return this;
  206. }
  207. /// <summary>
  208. /// Simulates a right click at the given screen coordinates on the current driver.
  209. /// This is a raw input event that goes through entire processing pipeline as though
  210. /// user had pressed the mouse button physically.
  211. /// </summary>
  212. /// <param name="screenX">0 indexed screen coordinates</param>
  213. /// <param name="screenY">0 indexed screen coordinates</param>
  214. /// <returns></returns>
  215. public GuiTestContext RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  216. /// <summary>
  217. /// Simulates a left click at the given screen coordinates on the current driver.
  218. /// This is a raw input event that goes through entire processing pipeline as though
  219. /// user had pressed the mouse button physically.
  220. /// </summary>
  221. /// <param name="screenX">0 indexed screen coordinates</param>
  222. /// <param name="screenY">0 indexed screen coordinates</param>
  223. /// <returns></returns>
  224. public GuiTestContext LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  225. private GuiTestContext Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  226. {
  227. switch (_driver)
  228. {
  229. case V2TestDriver.V2Win:
  230. _winInput.InputBuffer.Enqueue (
  231. new ()
  232. {
  233. EventType = WindowsConsole.EventType.Mouse,
  234. MouseEvent = new ()
  235. {
  236. ButtonState = btn,
  237. MousePosition = new ((short)screenX, (short)screenY)
  238. }
  239. });
  240. _winInput.InputBuffer.Enqueue (
  241. new ()
  242. {
  243. EventType = WindowsConsole.EventType.Mouse,
  244. MouseEvent = new ()
  245. {
  246. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  247. MousePosition = new ((short)screenX, (short)screenY)
  248. }
  249. });
  250. break;
  251. case V2TestDriver.V2Net:
  252. int netButton = btn switch
  253. {
  254. WindowsConsole.ButtonState.Button1Pressed => 0,
  255. WindowsConsole.ButtonState.Button2Pressed => 1,
  256. WindowsConsole.ButtonState.Button3Pressed => 2,
  257. WindowsConsole.ButtonState.RightmostButtonPressed => 2,
  258. _ => throw new ArgumentOutOfRangeException(nameof(btn))
  259. };
  260. foreach (var k in NetSequences.Click(netButton,screenX,screenY))
  261. {
  262. SendNetKey (k);
  263. }
  264. break;
  265. default:
  266. throw new ArgumentOutOfRangeException ();
  267. }
  268. WaitIteration ();
  269. return this;
  270. }
  271. public GuiTestContext Down ()
  272. {
  273. switch (_driver)
  274. {
  275. case V2TestDriver.V2Win:
  276. SendWindowsKey (ConsoleKeyMapping.VK.DOWN);
  277. WaitIteration ();
  278. break;
  279. case V2TestDriver.V2Net:
  280. foreach (var k in NetSequences.Down)
  281. {
  282. SendNetKey (k);
  283. }
  284. break;
  285. default:
  286. throw new ArgumentOutOfRangeException ();
  287. }
  288. return this;
  289. }
  290. /// <summary>
  291. /// Simulates the Right cursor key
  292. /// </summary>
  293. /// <returns></returns>
  294. /// <exception cref="ArgumentOutOfRangeException"></exception>
  295. public GuiTestContext Right ()
  296. {
  297. switch (_driver)
  298. {
  299. case V2TestDriver.V2Win:
  300. SendWindowsKey (ConsoleKeyMapping.VK.RIGHT);
  301. WaitIteration ();
  302. break;
  303. case V2TestDriver.V2Net:
  304. foreach (var k in NetSequences.Right)
  305. {
  306. SendNetKey (k);
  307. }
  308. break;
  309. default:
  310. throw new ArgumentOutOfRangeException ();
  311. }
  312. return this;
  313. }
  314. /// <summary>
  315. /// Simulates the Left cursor key
  316. /// </summary>
  317. /// <returns></returns>
  318. /// <exception cref="ArgumentOutOfRangeException"></exception>
  319. public GuiTestContext Left ()
  320. {
  321. switch (_driver)
  322. {
  323. case V2TestDriver.V2Win:
  324. SendWindowsKey (ConsoleKeyMapping.VK.LEFT);
  325. WaitIteration ();
  326. break;
  327. case V2TestDriver.V2Net:
  328. foreach (var k in NetSequences.Left)
  329. {
  330. SendNetKey (k);
  331. }
  332. break;
  333. default:
  334. throw new ArgumentOutOfRangeException ();
  335. }
  336. return this;
  337. }
  338. /// <summary>
  339. /// Simulates the up cursor key
  340. /// </summary>
  341. /// <returns></returns>
  342. /// <exception cref="ArgumentOutOfRangeException"></exception>
  343. public GuiTestContext Up ()
  344. {
  345. switch (_driver)
  346. {
  347. case V2TestDriver.V2Win:
  348. SendWindowsKey (ConsoleKeyMapping.VK.UP);
  349. WaitIteration ();
  350. break;
  351. case V2TestDriver.V2Net:
  352. foreach (var k in NetSequences.Up)
  353. {
  354. SendNetKey (k);
  355. }
  356. break;
  357. default:
  358. throw new ArgumentOutOfRangeException ();
  359. }
  360. return this;
  361. }
  362. /// <summary>
  363. /// Simulates pressing the Return/Enter (newline) key.
  364. /// </summary>
  365. /// <returns></returns>
  366. /// <exception cref="ArgumentOutOfRangeException"></exception>
  367. public GuiTestContext Enter ()
  368. {
  369. switch (_driver)
  370. {
  371. case V2TestDriver.V2Win:
  372. SendWindowsKey (
  373. new WindowsConsole.KeyEventRecord
  374. {
  375. UnicodeChar = '\r',
  376. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  377. wRepeatCount = 1,
  378. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  379. wVirtualScanCode = 28
  380. });
  381. break;
  382. case V2TestDriver.V2Net:
  383. SendNetKey (new ('\r', ConsoleKey.Enter, false, false, false));
  384. break;
  385. default:
  386. throw new ArgumentOutOfRangeException ();
  387. }
  388. return this;
  389. }
  390. /// <summary>
  391. /// Registers a right click handler on the <see cref="LastView"/> added view (or root view) that
  392. /// will open the supplied <paramref name="menuItems"/>.
  393. /// </summary>
  394. /// <param name="ctx"></param>
  395. /// <param name="menuItems"></param>
  396. /// <returns></returns>
  397. public GuiTestContext WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  398. {
  399. LastView.MouseEvent += (s, e) =>
  400. {
  401. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  402. {
  403. ctx.Show (menuItems);
  404. }
  405. };
  406. return this;
  407. }
  408. /// <summary>
  409. /// The last view added (e.g. with <see cref="Add"/>) or the root/current top.
  410. /// </summary>
  411. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  412. /// <summary>
  413. /// Send a full windows OS key including both down and up.
  414. /// </summary>
  415. /// <param name="fullKey"></param>
  416. private void SendWindowsKey (WindowsConsole.KeyEventRecord fullKey)
  417. {
  418. WindowsConsole.KeyEventRecord down = fullKey;
  419. WindowsConsole.KeyEventRecord up = fullKey; // because struct this is new copy
  420. down.bKeyDown = true;
  421. up.bKeyDown = false;
  422. _winInput.InputBuffer.Enqueue (
  423. new ()
  424. {
  425. EventType = WindowsConsole.EventType.Key,
  426. KeyEvent = down
  427. });
  428. _winInput.InputBuffer.Enqueue (
  429. new ()
  430. {
  431. EventType = WindowsConsole.EventType.Key,
  432. KeyEvent = up
  433. });
  434. WaitIteration ();
  435. }
  436. private void SendNetKey (ConsoleKeyInfo consoleKeyInfo)
  437. {
  438. _netInput.InputBuffer.Enqueue (consoleKeyInfo);
  439. }
  440. /// <summary>
  441. /// Sends a special key e.g. cursor key that does not map to a specific character
  442. /// </summary>
  443. /// <param name="specialKey"></param>
  444. private void SendWindowsKey (ConsoleKeyMapping.VK specialKey)
  445. {
  446. _winInput.InputBuffer.Enqueue (
  447. new ()
  448. {
  449. EventType = WindowsConsole.EventType.Key,
  450. KeyEvent = new ()
  451. {
  452. bKeyDown = true,
  453. wRepeatCount = 0,
  454. wVirtualKeyCode = specialKey,
  455. wVirtualScanCode = 0,
  456. UnicodeChar = '\0',
  457. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  458. }
  459. });
  460. _winInput.InputBuffer.Enqueue (
  461. new ()
  462. {
  463. EventType = WindowsConsole.EventType.Key,
  464. KeyEvent = new ()
  465. {
  466. bKeyDown = false,
  467. wRepeatCount = 0,
  468. wVirtualKeyCode = specialKey,
  469. wVirtualScanCode = 0,
  470. UnicodeChar = '\0',
  471. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  472. }
  473. });
  474. WaitIteration ();
  475. }
  476. }