Class1.cs 11 KB

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