GuiTestContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. 
  2. using Terminal.Gui;
  3. using Terminal.Gui.ConsoleDrivers;
  4. namespace TerminalGuiFluentTesting;
  5. public class GuiTestContext<T> : IDisposable where T : Toplevel, new ()
  6. {
  7. private readonly CancellationTokenSource _cts = new ();
  8. private readonly CancellationTokenSource _hardStop = new (With.Timeout);
  9. private readonly Task _runTask;
  10. private Exception _ex;
  11. private readonly FakeOutput _output = new ();
  12. private readonly FakeWindowsInput _winInput;
  13. private readonly FakeNetInput _netInput;
  14. private View _lastView;
  15. internal GuiTestContext (int width, int height)
  16. {
  17. IApplication origApp = ApplicationImpl.Instance;
  18. _netInput = new (_cts.Token);
  19. _winInput = new (_cts.Token);
  20. _output.Size = new (width, height);
  21. var v2 = new ApplicationV2 (
  22. () => _netInput,
  23. () => _output,
  24. () => _winInput,
  25. () => _output);
  26. var booting = new SemaphoreSlim (0, 1);
  27. // Start the application in a background thread
  28. _runTask = Task.Run (
  29. () =>
  30. {
  31. try
  32. {
  33. ApplicationImpl.ChangeInstance (v2);
  34. v2.Init (null, "v2win");
  35. booting.Release ();
  36. Application.Run<T> (); // This will block, but it's on a background thread now
  37. Application.Shutdown ();
  38. }
  39. catch (OperationCanceledException)
  40. { }
  41. catch (Exception ex)
  42. {
  43. _ex = ex;
  44. }
  45. finally
  46. {
  47. ApplicationImpl.ChangeInstance (origApp);
  48. }
  49. },
  50. _cts.Token);
  51. // Wait for booting to complete with a timeout to avoid hangs
  52. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  53. {
  54. throw new TimeoutException ("Application failed to start within the allotted time.");
  55. }
  56. WaitIteration ();
  57. }
  58. /// <summary>
  59. /// Stops the application and waits for the background thread to exit.
  60. /// </summary>
  61. public GuiTestContext<T> Stop ()
  62. {
  63. if (_runTask.IsCompleted)
  64. {
  65. return this;
  66. }
  67. Application.Invoke (() => Application.RequestStop ());
  68. // Wait for the application to stop, but give it a 1-second timeout
  69. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  70. {
  71. _cts.Cancel ();
  72. // Timeout occurred, force the task to stop
  73. _hardStop.Cancel ();
  74. throw new TimeoutException ("Application failed to stop within the allotted time.");
  75. }
  76. _cts.Cancel ();
  77. if (_ex != null)
  78. {
  79. throw _ex; // Propagate any exception that happened in the background task
  80. }
  81. return this;
  82. }
  83. // Cleanup to avoid state bleed between tests
  84. public void Dispose ()
  85. {
  86. Stop ();
  87. if (_hardStop.IsCancellationRequested)
  88. {
  89. throw new (
  90. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  91. }
  92. _hardStop.Cancel ();
  93. }
  94. /// <summary>
  95. /// Adds the given <paramref name="v"/> to the current top level view
  96. /// and performs layout.
  97. /// </summary>
  98. /// <param name="v"></param>
  99. /// <returns></returns>
  100. public GuiTestContext<T> Add (View v)
  101. {
  102. WaitIteration (
  103. () =>
  104. {
  105. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  106. top.Add (v);
  107. top.Layout ();
  108. _lastView = v;
  109. });
  110. return this;
  111. }
  112. public GuiTestContext<T> ResizeConsole (int width, int height)
  113. {
  114. _output.Size = new (width, height);
  115. return WaitIteration ();
  116. }
  117. public GuiTestContext<T> ScreenShot (string title, TextWriter writer)
  118. {
  119. writer.WriteLine (title + ":");
  120. var text = Application.ToString ();
  121. writer.WriteLine (text);
  122. return WaitIteration ();
  123. }
  124. public GuiTestContext<T> WaitIteration (Action? a = null)
  125. {
  126. a ??= () => { };
  127. var ctsLocal = new CancellationTokenSource ();
  128. Application.Invoke (
  129. () =>
  130. {
  131. a ();
  132. ctsLocal.Cancel ();
  133. });
  134. // Blocks until either the token or the hardStopToken is cancelled.
  135. WaitHandle.WaitAny (
  136. new []
  137. {
  138. _cts.Token.WaitHandle,
  139. _hardStop.Token.WaitHandle,
  140. ctsLocal.Token.WaitHandle
  141. });
  142. return this;
  143. }
  144. public GuiTestContext<T> Then (Action doAction)
  145. {
  146. doAction ();
  147. return this;
  148. }
  149. public GuiTestContext<T> RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  150. public GuiTestContext<T> LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  151. private GuiTestContext<T> Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  152. {
  153. _winInput.InputBuffer.Enqueue (
  154. new()
  155. {
  156. EventType = WindowsConsole.EventType.Mouse,
  157. MouseEvent = new()
  158. {
  159. ButtonState = btn,
  160. MousePosition = new ((short)screenX, (short)screenY)
  161. }
  162. });
  163. _winInput.InputBuffer.Enqueue (
  164. new()
  165. {
  166. EventType = WindowsConsole.EventType.Mouse,
  167. MouseEvent = new()
  168. {
  169. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  170. MousePosition = new ((short)screenX, (short)screenY)
  171. }
  172. });
  173. WaitIteration ();
  174. return this;
  175. }
  176. public GuiTestContext<T> Down ()
  177. {
  178. _winInput.InputBuffer.Enqueue (
  179. new()
  180. {
  181. EventType = WindowsConsole.EventType.Key,
  182. KeyEvent = new()
  183. {
  184. bKeyDown = true,
  185. wRepeatCount = 0,
  186. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  187. wVirtualScanCode = 0,
  188. UnicodeChar = '\0',
  189. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  190. }
  191. });
  192. _winInput.InputBuffer.Enqueue (
  193. new()
  194. {
  195. EventType = WindowsConsole.EventType.Key,
  196. KeyEvent = new()
  197. {
  198. bKeyDown = false,
  199. wRepeatCount = 0,
  200. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  201. wVirtualScanCode = 0,
  202. UnicodeChar = '\0',
  203. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  204. }
  205. });
  206. WaitIteration ();
  207. return this;
  208. }
  209. public GuiTestContext<T> Enter ()
  210. {
  211. _winInput.InputBuffer.Enqueue (
  212. new()
  213. {
  214. EventType = WindowsConsole.EventType.Key,
  215. KeyEvent = new()
  216. {
  217. bKeyDown = true,
  218. wRepeatCount = 0,
  219. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  220. wVirtualScanCode = 0,
  221. UnicodeChar = '\0',
  222. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  223. }
  224. });
  225. _winInput.InputBuffer.Enqueue (
  226. new()
  227. {
  228. EventType = WindowsConsole.EventType.Key,
  229. KeyEvent = new()
  230. {
  231. bKeyDown = false,
  232. wRepeatCount = 0,
  233. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  234. wVirtualScanCode = 0,
  235. UnicodeChar = '\0',
  236. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  237. }
  238. });
  239. WaitIteration ();
  240. return this;
  241. }
  242. public GuiTestContext<T> WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  243. {
  244. LastView.MouseEvent += (s, e) =>
  245. {
  246. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  247. {
  248. ctx.Show (menuItems);
  249. }
  250. };
  251. return this;
  252. }
  253. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  254. }