GuiTestContext.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. internal GuiTestContext (Func<Toplevel> topLevelBuilder, int width, int height)
  18. {
  19. IApplication origApp = ApplicationImpl.Instance;
  20. ILogger? origLogger = Logging.Logger;
  21. _logsSb = new ();
  22. _netInput = new (_cts.Token);
  23. _winInput = new (_cts.Token);
  24. _output.Size = new (width, height);
  25. var v2 = new ApplicationV2 (
  26. () => _netInput,
  27. () => _output,
  28. () => _winInput,
  29. () => _output);
  30. var booting = new SemaphoreSlim (0, 1);
  31. // Start the application in a background thread
  32. _runTask = Task.Run (
  33. () =>
  34. {
  35. try
  36. {
  37. ApplicationImpl.ChangeInstance (v2);
  38. ILogger logger = LoggerFactory.Create (
  39. builder =>
  40. builder.SetMinimumLevel (LogLevel.Trace)
  41. .AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb))))
  42. .CreateLogger ("Test Logging");
  43. Logging.Logger = logger;
  44. v2.Init (null, "v2win");
  45. booting.Release ();
  46. Toplevel t = topLevelBuilder ();
  47. Application.Run (t); // This will block, but it's on a background thread now
  48. Application.Shutdown ();
  49. }
  50. catch (OperationCanceledException)
  51. { }
  52. catch (Exception ex)
  53. {
  54. _ex = ex;
  55. }
  56. finally
  57. {
  58. ApplicationImpl.ChangeInstance (origApp);
  59. Logging.Logger = origLogger;
  60. }
  61. },
  62. _cts.Token);
  63. // Wait for booting to complete with a timeout to avoid hangs
  64. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  65. {
  66. throw new TimeoutException ("Application failed to start within the allotted time.");
  67. }
  68. WaitIteration ();
  69. }
  70. /// <summary>
  71. /// Stops the application and waits for the background thread to exit.
  72. /// </summary>
  73. public GuiTestContext Stop ()
  74. {
  75. if (_runTask.IsCompleted)
  76. {
  77. return this;
  78. }
  79. Application.Invoke (() => Application.RequestStop ());
  80. // Wait for the application to stop, but give it a 1-second timeout
  81. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  82. {
  83. _cts.Cancel ();
  84. // Timeout occurred, force the task to stop
  85. _hardStop.Cancel ();
  86. throw new TimeoutException ("Application failed to stop within the allotted time.");
  87. }
  88. _cts.Cancel ();
  89. if (_ex != null)
  90. {
  91. throw _ex; // Propagate any exception that happened in the background task
  92. }
  93. return this;
  94. }
  95. // Cleanup to avoid state bleed between tests
  96. public void Dispose ()
  97. {
  98. Stop ();
  99. if (_hardStop.IsCancellationRequested)
  100. {
  101. throw new (
  102. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  103. }
  104. _hardStop.Cancel ();
  105. }
  106. /// <summary>
  107. /// Adds the given <paramref name="v"/> to the current top level view
  108. /// and performs layout.
  109. /// </summary>
  110. /// <param name="v"></param>
  111. /// <returns></returns>
  112. public GuiTestContext Add (View v)
  113. {
  114. WaitIteration (
  115. () =>
  116. {
  117. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  118. top.Add (v);
  119. top.Layout ();
  120. _lastView = v;
  121. });
  122. return this;
  123. }
  124. public GuiTestContext ResizeConsole (int width, int height)
  125. {
  126. _output.Size = new (width, height);
  127. return WaitIteration ();
  128. }
  129. public GuiTestContext ScreenShot (string title, TextWriter writer)
  130. {
  131. writer.WriteLine (title + ":");
  132. var text = Application.ToString ();
  133. writer.WriteLine (text);
  134. return WaitIteration ();
  135. }
  136. public GuiTestContext WriteOutLogs (TextWriter writer)
  137. {
  138. writer.WriteLine (_logsSb.ToString ());
  139. return WaitIteration ();
  140. }
  141. public GuiTestContext WaitIteration (Action? a = null)
  142. {
  143. a ??= () => { };
  144. var ctsLocal = new CancellationTokenSource ();
  145. Application.Invoke (
  146. () =>
  147. {
  148. a ();
  149. ctsLocal.Cancel ();
  150. });
  151. // Blocks until either the token or the hardStopToken is cancelled.
  152. WaitHandle.WaitAny (
  153. new []
  154. {
  155. _cts.Token.WaitHandle,
  156. _hardStop.Token.WaitHandle,
  157. ctsLocal.Token.WaitHandle
  158. });
  159. return this;
  160. }
  161. public GuiTestContext Then (Action doAction)
  162. {
  163. doAction ();
  164. return this;
  165. }
  166. public GuiTestContext RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  167. public GuiTestContext LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  168. private GuiTestContext Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  169. {
  170. _winInput.InputBuffer.Enqueue (
  171. new ()
  172. {
  173. EventType = WindowsConsole.EventType.Mouse,
  174. MouseEvent = new ()
  175. {
  176. ButtonState = btn,
  177. MousePosition = new ((short)screenX, (short)screenY)
  178. }
  179. });
  180. _winInput.InputBuffer.Enqueue (
  181. new ()
  182. {
  183. EventType = WindowsConsole.EventType.Mouse,
  184. MouseEvent = new ()
  185. {
  186. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  187. MousePosition = new ((short)screenX, (short)screenY)
  188. }
  189. });
  190. WaitIteration ();
  191. return this;
  192. }
  193. public GuiTestContext Down ()
  194. {
  195. SendWindowsKey (ConsoleKeyMapping.VK.DOWN);
  196. return this;
  197. }
  198. public GuiTestContext Right ()
  199. {
  200. SendWindowsKey (ConsoleKeyMapping.VK.RIGHT);
  201. return this;
  202. }
  203. public GuiTestContext Left ()
  204. {
  205. SendWindowsKey (ConsoleKeyMapping.VK.LEFT);
  206. return this;
  207. }
  208. public GuiTestContext Up ()
  209. {
  210. SendWindowsKey (ConsoleKeyMapping.VK.UP);
  211. return this;
  212. }
  213. public GuiTestContext Enter ()
  214. {
  215. SendWindowsKey (
  216. new WindowsConsole.KeyEventRecord
  217. {
  218. UnicodeChar = '\r',
  219. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  220. wRepeatCount = 1,
  221. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  222. wVirtualScanCode = 28
  223. });
  224. return this;
  225. }
  226. /// <summary>
  227. /// Send a full windows OS key including both down and up.
  228. /// </summary>
  229. /// <param name="fullKey"></param>
  230. private void SendWindowsKey (WindowsConsole.KeyEventRecord fullKey)
  231. {
  232. WindowsConsole.KeyEventRecord down = fullKey;
  233. WindowsConsole.KeyEventRecord up = fullKey; // because struct this is new copy
  234. down.bKeyDown = true;
  235. up.bKeyDown = false;
  236. _winInput.InputBuffer.Enqueue (
  237. new ()
  238. {
  239. EventType = WindowsConsole.EventType.Key,
  240. KeyEvent = down
  241. });
  242. _winInput.InputBuffer.Enqueue (
  243. new ()
  244. {
  245. EventType = WindowsConsole.EventType.Key,
  246. KeyEvent = up
  247. });
  248. WaitIteration ();
  249. }
  250. /// <summary>
  251. /// Sends a special key e.g. cursor key that does not map to a specific character
  252. /// </summary>
  253. /// <param name="specialKey"></param>
  254. private void SendWindowsKey (ConsoleKeyMapping.VK specialKey)
  255. {
  256. _winInput.InputBuffer.Enqueue (
  257. new ()
  258. {
  259. EventType = WindowsConsole.EventType.Key,
  260. KeyEvent = new ()
  261. {
  262. bKeyDown = true,
  263. wRepeatCount = 0,
  264. wVirtualKeyCode = specialKey,
  265. wVirtualScanCode = 0,
  266. UnicodeChar = '\0',
  267. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  268. }
  269. });
  270. _winInput.InputBuffer.Enqueue (
  271. new ()
  272. {
  273. EventType = WindowsConsole.EventType.Key,
  274. KeyEvent = new ()
  275. {
  276. bKeyDown = false,
  277. wRepeatCount = 0,
  278. wVirtualKeyCode = specialKey,
  279. wVirtualScanCode = 0,
  280. UnicodeChar = '\0',
  281. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  282. }
  283. });
  284. WaitIteration ();
  285. }
  286. public GuiTestContext WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  287. {
  288. LastView.MouseEvent += (s, e) =>
  289. {
  290. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  291. {
  292. ctx.Show (menuItems);
  293. }
  294. };
  295. return this;
  296. }
  297. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  298. }