GuiTestContext.cs 13 KB

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