GuiTestContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. using FluentAssertions;
  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> Assert<T2> (AndConstraint<T2> be) { return this; }
  145. public GuiTestContext<T> RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  146. public GuiTestContext<T> LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  147. private GuiTestContext<T> Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  148. {
  149. _winInput.InputBuffer.Enqueue (
  150. new()
  151. {
  152. EventType = WindowsConsole.EventType.Mouse,
  153. MouseEvent = new()
  154. {
  155. ButtonState = btn,
  156. MousePosition = new ((short)screenX, (short)screenY)
  157. }
  158. });
  159. _winInput.InputBuffer.Enqueue (
  160. new()
  161. {
  162. EventType = WindowsConsole.EventType.Mouse,
  163. MouseEvent = new()
  164. {
  165. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  166. MousePosition = new ((short)screenX, (short)screenY)
  167. }
  168. });
  169. WaitIteration ();
  170. return this;
  171. }
  172. public GuiTestContext<T> Down ()
  173. {
  174. _winInput.InputBuffer.Enqueue (
  175. new()
  176. {
  177. EventType = WindowsConsole.EventType.Key,
  178. KeyEvent = new()
  179. {
  180. bKeyDown = true,
  181. wRepeatCount = 0,
  182. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  183. wVirtualScanCode = 0,
  184. UnicodeChar = '\0',
  185. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  186. }
  187. });
  188. _winInput.InputBuffer.Enqueue (
  189. new()
  190. {
  191. EventType = WindowsConsole.EventType.Key,
  192. KeyEvent = new()
  193. {
  194. bKeyDown = false,
  195. wRepeatCount = 0,
  196. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  197. wVirtualScanCode = 0,
  198. UnicodeChar = '\0',
  199. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  200. }
  201. });
  202. WaitIteration ();
  203. return this;
  204. }
  205. public GuiTestContext<T> Enter ()
  206. {
  207. _winInput.InputBuffer.Enqueue (
  208. new()
  209. {
  210. EventType = WindowsConsole.EventType.Key,
  211. KeyEvent = new()
  212. {
  213. bKeyDown = true,
  214. wRepeatCount = 0,
  215. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  216. wVirtualScanCode = 0,
  217. UnicodeChar = '\0',
  218. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  219. }
  220. });
  221. _winInput.InputBuffer.Enqueue (
  222. new()
  223. {
  224. EventType = WindowsConsole.EventType.Key,
  225. KeyEvent = new()
  226. {
  227. bKeyDown = false,
  228. wRepeatCount = 0,
  229. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  230. wVirtualScanCode = 0,
  231. UnicodeChar = '\0',
  232. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  233. }
  234. });
  235. WaitIteration ();
  236. return this;
  237. }
  238. public GuiTestContext<T> WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  239. {
  240. LastView.MouseEvent += (s, e) =>
  241. {
  242. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  243. {
  244. ctx.Show (menuItems);
  245. }
  246. };
  247. return this;
  248. }
  249. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  250. }