Class1.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System.Collections.Concurrent;
  2. using System.Drawing;
  3. using FluentAssertions;
  4. using FluentAssertions.Numeric;
  5. using Terminal.Gui;
  6. using Terminal.Gui.ConsoleDrivers;
  7. using static Unix.Terminal.Curses;
  8. namespace TerminalGuiFluentAssertions;
  9. class FakeInput<T> : IConsoleInput<T>
  10. {
  11. private readonly CancellationToken _hardStopToken;
  12. private readonly CancellationTokenSource _timeoutCts;
  13. public FakeInput (CancellationToken hardStopToken)
  14. {
  15. _hardStopToken = hardStopToken;
  16. // Create a timeout-based cancellation token too to prevent tests ever fully hanging
  17. _timeoutCts = new (With.Timeout);
  18. }
  19. /// <inheritdoc />
  20. public void Dispose () { }
  21. /// <inheritdoc />
  22. public void Initialize (ConcurrentQueue<T> inputBuffer) { InputBuffer = inputBuffer;}
  23. public ConcurrentQueue<T> InputBuffer { get; set; }
  24. /// <inheritdoc />
  25. public void Run (CancellationToken token)
  26. {
  27. // Blocks until either the token or the hardStopToken is cancelled.
  28. WaitHandle.WaitAny (new [] { token.WaitHandle, _hardStopToken.WaitHandle, _timeoutCts.Token.WaitHandle });
  29. }
  30. }
  31. class FakeNetInput (CancellationToken hardStopToken) : FakeInput<ConsoleKeyInfo> (hardStopToken), INetInput
  32. {
  33. }
  34. class FakeWindowsInput (CancellationToken hardStopToken) : FakeInput<WindowsConsole.InputRecord> (hardStopToken), IWindowsInput
  35. {
  36. }
  37. class FakeOutput : IConsoleOutput
  38. {
  39. public IOutputBuffer LastBuffer { get; set; }
  40. public Size Size { get; set; }
  41. /// <inheritdoc />
  42. public void Dispose ()
  43. {
  44. }
  45. /// <inheritdoc />
  46. public void Write (ReadOnlySpan<char> text)
  47. {
  48. }
  49. /// <inheritdoc />
  50. public void Write (IOutputBuffer buffer)
  51. {
  52. LastBuffer = buffer;
  53. }
  54. /// <inheritdoc />
  55. public Size GetWindowSize ()
  56. {
  57. return Size;
  58. }
  59. /// <inheritdoc />
  60. public void SetCursorVisibility (CursorVisibility visibility)
  61. {
  62. }
  63. /// <inheritdoc />
  64. public void SetCursorPosition (int col, int row)
  65. {
  66. }
  67. }
  68. /// <summary>
  69. /// Entry point to fluent assertions.
  70. /// </summary>
  71. public static class With
  72. {
  73. /// <summary>
  74. /// Entrypoint to fluent assertions
  75. /// </summary>
  76. /// <param name="width"></param>
  77. /// <param name="height"></param>
  78. /// <returns></returns>
  79. public static GuiTestContext<T> A<T> (int width, int height) where T : Toplevel, new ()
  80. {
  81. return new (width,height);
  82. }
  83. /// <summary>
  84. /// The global timeout to allow for any given application to run for before shutting down.
  85. /// </summary>
  86. public static TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds (30);
  87. }
  88. public class GuiTestContext<T> : IDisposable where T : Toplevel, new()
  89. {
  90. private readonly CancellationTokenSource _cts = new ();
  91. private readonly CancellationTokenSource _hardStop = new (With.Timeout);
  92. private readonly Task _runTask;
  93. private Exception _ex;
  94. private readonly FakeOutput _output = new ();
  95. private readonly FakeWindowsInput winInput;
  96. private View _lastView;
  97. internal GuiTestContext (int width, int height)
  98. {
  99. IApplication origApp = ApplicationImpl.Instance;
  100. var netInput = new FakeNetInput (_cts.Token);
  101. winInput = new FakeWindowsInput (_cts.Token);
  102. _output.Size = new (width, height);
  103. var v2 = new ApplicationV2(
  104. () => netInput,
  105. ()=>_output,
  106. () => winInput,
  107. () => _output);
  108. var booting = new SemaphoreSlim (0, 1);
  109. // Start the application in a background thread
  110. _runTask = Task.Run (() =>
  111. {
  112. try
  113. {
  114. ApplicationImpl.ChangeInstance (v2);
  115. v2.Init (null,"v2win");
  116. booting.Release ();
  117. Application.Run<T> (); // This will block, but it's on a background thread now
  118. Application.Shutdown ();
  119. }
  120. catch (OperationCanceledException)
  121. { }
  122. catch (Exception ex)
  123. {
  124. _ex = ex;
  125. }
  126. finally
  127. {
  128. ApplicationImpl.ChangeInstance (origApp);
  129. }
  130. }, _cts.Token);
  131. // Wait for booting to complete with a timeout to avoid hangs
  132. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  133. {
  134. throw new TimeoutException ("Application failed to start within the allotted time.");
  135. }
  136. WaitIteration ();
  137. }
  138. /// <summary>
  139. /// Stops the application and waits for the background thread to exit.
  140. /// </summary>
  141. public GuiTestContext<T> Stop ()
  142. {
  143. if (_runTask.IsCompleted)
  144. {
  145. return this;
  146. }
  147. Application.Invoke (()=> Application.RequestStop ());
  148. // Wait for the application to stop, but give it a 1-second timeout
  149. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  150. {
  151. _cts.Cancel ();
  152. // Timeout occurred, force the task to stop
  153. _hardStop.Cancel ();
  154. throw new TimeoutException ("Application failed to stop within the allotted time.");
  155. }
  156. _cts.Cancel ();
  157. if (_ex != null)
  158. {
  159. throw _ex; // Propagate any exception that happened in the background task
  160. }
  161. return this;
  162. }
  163. // Cleanup to avoid state bleed between tests
  164. public void Dispose ()
  165. {
  166. Stop ();
  167. if (_hardStop.IsCancellationRequested)
  168. {
  169. throw new Exception (
  170. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  171. }
  172. _hardStop.Cancel();
  173. }
  174. /// <summary>
  175. /// Adds the given <paramref name="v"/> to the current top level view
  176. /// and performs layout.
  177. /// </summary>
  178. /// <param name="v"></param>
  179. /// <returns></returns>
  180. public GuiTestContext<T> Add (View v)
  181. {
  182. WaitIteration (
  183. () =>
  184. {
  185. var top = Application.Top ?? throw new Exception("Top was null so could not add view");
  186. top.Add (v);
  187. top.Layout ();
  188. _lastView = v;
  189. });
  190. return this;
  191. }
  192. public GuiTestContext<T> ResizeConsole (int width, int height)
  193. {
  194. _output.Size = new Size (width,height);
  195. return WaitIteration ();
  196. }
  197. public GuiTestContext<T> ScreenShot (string title, TextWriter writer)
  198. {
  199. writer.WriteLine(title +":");
  200. var text = Application.ToString ();
  201. writer.WriteLine(text);
  202. return WaitIteration ();
  203. }
  204. public GuiTestContext<T> WaitIteration (Action? a = null)
  205. {
  206. a ??= () => { };
  207. var ctsLocal = new CancellationTokenSource ();
  208. Application.Invoke (()=>
  209. {
  210. a();
  211. ctsLocal.Cancel ();
  212. });
  213. // Blocks until either the token or the hardStopToken is cancelled.
  214. WaitHandle.WaitAny (new []
  215. {
  216. _cts.Token.WaitHandle,
  217. _hardStop.Token.WaitHandle,
  218. ctsLocal.Token.WaitHandle
  219. });
  220. return this;
  221. }
  222. public GuiTestContext<T> Assert<T2> (AndConstraint<T2> be)
  223. {
  224. return this;
  225. }
  226. public GuiTestContext<T> RightClick (int screenX, int screenY)
  227. {
  228. return Click (WindowsConsole.ButtonState.Button3Pressed,screenX, screenY);
  229. }
  230. public GuiTestContext<T> LeftClick (int screenX, int screenY)
  231. {
  232. return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY);
  233. }
  234. private GuiTestContext<T> Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  235. {
  236. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  237. {
  238. EventType = WindowsConsole.EventType.Mouse,
  239. MouseEvent = new WindowsConsole.MouseEventRecord ()
  240. {
  241. ButtonState = btn,
  242. MousePosition = new WindowsConsole.Coord ((short)screenX, (short)screenY)
  243. }
  244. });
  245. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  246. {
  247. EventType = WindowsConsole.EventType.Mouse,
  248. MouseEvent = new WindowsConsole.MouseEventRecord ()
  249. {
  250. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  251. MousePosition = new WindowsConsole.Coord ((short)screenX, (short)screenY)
  252. }
  253. });
  254. WaitIteration ();
  255. return this;
  256. }
  257. public GuiTestContext<T> Down ()
  258. {
  259. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  260. {
  261. EventType = WindowsConsole.EventType.Key,
  262. KeyEvent = new WindowsConsole.KeyEventRecord
  263. {
  264. bKeyDown = true,
  265. wRepeatCount = 0,
  266. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  267. wVirtualScanCode = 0,
  268. UnicodeChar = '\0',
  269. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  270. }
  271. });
  272. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  273. {
  274. EventType = WindowsConsole.EventType.Key,
  275. KeyEvent = new WindowsConsole.KeyEventRecord
  276. {
  277. bKeyDown = false,
  278. wRepeatCount = 0,
  279. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  280. wVirtualScanCode = 0,
  281. UnicodeChar = '\0',
  282. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  283. }
  284. });
  285. WaitIteration ();
  286. return this;
  287. }
  288. public GuiTestContext<T> Enter ()
  289. {
  290. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  291. {
  292. EventType = WindowsConsole.EventType.Key,
  293. KeyEvent = new WindowsConsole.KeyEventRecord
  294. {
  295. bKeyDown = true,
  296. wRepeatCount = 0,
  297. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  298. wVirtualScanCode = 0,
  299. UnicodeChar = '\0',
  300. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  301. }
  302. });
  303. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  304. {
  305. EventType = WindowsConsole.EventType.Key,
  306. KeyEvent = new WindowsConsole.KeyEventRecord
  307. {
  308. bKeyDown = false,
  309. wRepeatCount = 0,
  310. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  311. wVirtualScanCode = 0,
  312. UnicodeChar = '\0',
  313. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  314. }
  315. });
  316. WaitIteration ();
  317. return this;
  318. }
  319. public GuiTestContext<T> WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  320. {
  321. LastView.MouseEvent += (s, e) =>
  322. {
  323. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  324. {
  325. ctx.Show (menuItems);
  326. }
  327. };
  328. return this;
  329. }
  330. public View LastView => _lastView ?? Application.Top ?? throw new Exception ("Could not determine which view to add to");
  331. }