GuiTestContext.cs 16 KB

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