GuiTestContext.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. // TODO: Support net style ansi escape sequence generation for arrow keys
  183. _winInput.InputBuffer.Enqueue (
  184. new ()
  185. {
  186. EventType = WindowsConsole.EventType.Mouse,
  187. MouseEvent = new ()
  188. {
  189. ButtonState = btn,
  190. MousePosition = new ((short)screenX, (short)screenY)
  191. }
  192. });
  193. _winInput.InputBuffer.Enqueue (
  194. new ()
  195. {
  196. EventType = WindowsConsole.EventType.Mouse,
  197. MouseEvent = new ()
  198. {
  199. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  200. MousePosition = new ((short)screenX, (short)screenY)
  201. }
  202. });
  203. WaitIteration ();
  204. return this;
  205. }
  206. public GuiTestContext Down ()
  207. {
  208. switch (_driver)
  209. {
  210. case V2TestDriver.V2Win:
  211. SendWindowsKey (ConsoleKeyMapping.VK.DOWN);
  212. break;
  213. case V2TestDriver.V2Net:
  214. // TODO: Support ansi sequence
  215. throw new NotImplementedException ("Coming soon");
  216. break;
  217. default:
  218. throw new ArgumentOutOfRangeException ();
  219. }
  220. return this;
  221. }
  222. public GuiTestContext Right ()
  223. {
  224. SendWindowsKey (ConsoleKeyMapping.VK.RIGHT);
  225. return this;
  226. }
  227. public GuiTestContext Left ()
  228. {
  229. SendWindowsKey (ConsoleKeyMapping.VK.LEFT);
  230. return this;
  231. }
  232. public GuiTestContext Up ()
  233. {
  234. SendWindowsKey (ConsoleKeyMapping.VK.UP);
  235. return this;
  236. }
  237. public GuiTestContext Enter ()
  238. {
  239. switch (_driver)
  240. {
  241. case V2TestDriver.V2Win:
  242. SendWindowsKey (
  243. new WindowsConsole.KeyEventRecord
  244. {
  245. UnicodeChar = '\r',
  246. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  247. wRepeatCount = 1,
  248. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  249. wVirtualScanCode = 28
  250. });
  251. break;
  252. case V2TestDriver.V2Net:
  253. SendNetKey (new ('\r', ConsoleKey.Enter, false, false, false));
  254. break;
  255. default:
  256. throw new ArgumentOutOfRangeException ();
  257. }
  258. return this;
  259. }
  260. /// <summary>
  261. /// Send a full windows OS key including both down and up.
  262. /// </summary>
  263. /// <param name="fullKey"></param>
  264. private void SendWindowsKey (WindowsConsole.KeyEventRecord fullKey)
  265. {
  266. WindowsConsole.KeyEventRecord down = fullKey;
  267. WindowsConsole.KeyEventRecord up = fullKey; // because struct this is new copy
  268. down.bKeyDown = true;
  269. up.bKeyDown = false;
  270. _winInput.InputBuffer.Enqueue (
  271. new ()
  272. {
  273. EventType = WindowsConsole.EventType.Key,
  274. KeyEvent = down
  275. });
  276. _winInput.InputBuffer.Enqueue (
  277. new ()
  278. {
  279. EventType = WindowsConsole.EventType.Key,
  280. KeyEvent = up
  281. });
  282. WaitIteration ();
  283. }
  284. private void SendNetKey (ConsoleKeyInfo consoleKeyInfo)
  285. {
  286. _netInput.InputBuffer.Enqueue (consoleKeyInfo);
  287. WaitIteration ();
  288. }
  289. /// <summary>
  290. /// Sends a special key e.g. cursor key that does not map to a specific character
  291. /// </summary>
  292. /// <param name="specialKey"></param>
  293. private void SendWindowsKey (ConsoleKeyMapping.VK specialKey)
  294. {
  295. _winInput.InputBuffer.Enqueue (
  296. new ()
  297. {
  298. EventType = WindowsConsole.EventType.Key,
  299. KeyEvent = new ()
  300. {
  301. bKeyDown = true,
  302. wRepeatCount = 0,
  303. wVirtualKeyCode = specialKey,
  304. wVirtualScanCode = 0,
  305. UnicodeChar = '\0',
  306. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  307. }
  308. });
  309. _winInput.InputBuffer.Enqueue (
  310. new ()
  311. {
  312. EventType = WindowsConsole.EventType.Key,
  313. KeyEvent = new ()
  314. {
  315. bKeyDown = false,
  316. wRepeatCount = 0,
  317. wVirtualKeyCode = specialKey,
  318. wVirtualScanCode = 0,
  319. UnicodeChar = '\0',
  320. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  321. }
  322. });
  323. WaitIteration ();
  324. }
  325. public GuiTestContext WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  326. {
  327. LastView.MouseEvent += (s, e) =>
  328. {
  329. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  330. {
  331. ctx.Show (menuItems);
  332. }
  333. };
  334. return this;
  335. }
  336. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  337. }