GuiTestContext.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb))))
  54. .CreateLogger ("Test Logging");
  55. Logging.Logger = logger;
  56. v2.Init (null, "v2win");
  57. booting.Release ();
  58. var t = topLevelBuilder ();
  59. Application.Run(t); // This will block, but it's on a background thread now
  60. Application.Shutdown ();
  61. }
  62. catch (OperationCanceledException)
  63. { }
  64. catch (Exception ex)
  65. {
  66. _ex = ex;
  67. }
  68. finally
  69. {
  70. ApplicationImpl.ChangeInstance (origApp);
  71. Logging.Logger = origLogger;
  72. }
  73. },
  74. _cts.Token);
  75. // Wait for booting to complete with a timeout to avoid hangs
  76. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  77. {
  78. throw new TimeoutException ("Application failed to start within the allotted time.");
  79. }
  80. WaitIteration ();
  81. }
  82. /// <summary>
  83. /// Stops the application and waits for the background thread to exit.
  84. /// </summary>
  85. public GuiTestContext Stop ()
  86. {
  87. if (_runTask.IsCompleted)
  88. {
  89. return this;
  90. }
  91. Application.Invoke (() => Application.RequestStop ());
  92. // Wait for the application to stop, but give it a 1-second timeout
  93. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  94. {
  95. _cts.Cancel ();
  96. // Timeout occurred, force the task to stop
  97. _hardStop.Cancel ();
  98. throw new TimeoutException ("Application failed to stop within the allotted time.");
  99. }
  100. _cts.Cancel ();
  101. if (_ex != null)
  102. {
  103. throw _ex; // Propagate any exception that happened in the background task
  104. }
  105. return this;
  106. }
  107. // Cleanup to avoid state bleed between tests
  108. public void Dispose ()
  109. {
  110. Stop ();
  111. if (_hardStop.IsCancellationRequested)
  112. {
  113. throw new (
  114. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  115. }
  116. _hardStop.Cancel ();
  117. }
  118. /// <summary>
  119. /// Adds the given <paramref name="v"/> to the current top level view
  120. /// and performs layout.
  121. /// </summary>
  122. /// <param name="v"></param>
  123. /// <returns></returns>
  124. public GuiTestContext Add (View v)
  125. {
  126. WaitIteration (
  127. () =>
  128. {
  129. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  130. top.Add (v);
  131. top.Layout ();
  132. _lastView = v;
  133. });
  134. return this;
  135. }
  136. public GuiTestContext ResizeConsole (int width, int height)
  137. {
  138. _output.Size = new (width, height);
  139. return WaitIteration ();
  140. }
  141. public GuiTestContext ScreenShot (string title, TextWriter writer)
  142. {
  143. writer.WriteLine (title + ":");
  144. var text = Application.ToString ();
  145. writer.WriteLine (text);
  146. return WaitIteration ();
  147. }
  148. public GuiTestContext WriteOutLogs (TextWriter writer)
  149. {
  150. writer.WriteLine (_logsSb.ToString());
  151. return WaitIteration ();
  152. }
  153. public GuiTestContext WaitIteration (Action? a = null)
  154. {
  155. a ??= () => { };
  156. var ctsLocal = new CancellationTokenSource ();
  157. Application.Invoke (
  158. () =>
  159. {
  160. a ();
  161. ctsLocal.Cancel ();
  162. });
  163. // Blocks until either the token or the hardStopToken is cancelled.
  164. WaitHandle.WaitAny (
  165. new []
  166. {
  167. _cts.Token.WaitHandle,
  168. _hardStop.Token.WaitHandle,
  169. ctsLocal.Token.WaitHandle
  170. });
  171. return this;
  172. }
  173. public GuiTestContext Then (Action doAction)
  174. {
  175. doAction ();
  176. return this;
  177. }
  178. public GuiTestContext RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  179. public GuiTestContext LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  180. private GuiTestContext Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  181. {
  182. _winInput.InputBuffer.Enqueue (
  183. new()
  184. {
  185. EventType = WindowsConsole.EventType.Mouse,
  186. MouseEvent = new()
  187. {
  188. ButtonState = btn,
  189. MousePosition = new ((short)screenX, (short)screenY)
  190. }
  191. });
  192. _winInput.InputBuffer.Enqueue (
  193. new()
  194. {
  195. EventType = WindowsConsole.EventType.Mouse,
  196. MouseEvent = new()
  197. {
  198. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  199. MousePosition = new ((short)screenX, (short)screenY)
  200. }
  201. });
  202. WaitIteration ();
  203. return this;
  204. }
  205. public GuiTestContext Down ()
  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.DOWN,
  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.DOWN,
  230. wVirtualScanCode = 0,
  231. UnicodeChar = '\0',
  232. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  233. }
  234. });
  235. WaitIteration ();
  236. return this;
  237. }
  238. public GuiTestContext Enter ()
  239. {
  240. _winInput.InputBuffer.Enqueue (
  241. new()
  242. {
  243. EventType = WindowsConsole.EventType.Key,
  244. KeyEvent = new()
  245. {
  246. bKeyDown = true,
  247. wRepeatCount = 0,
  248. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  249. wVirtualScanCode = 0,
  250. UnicodeChar = '\0',
  251. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  252. }
  253. });
  254. _winInput.InputBuffer.Enqueue (
  255. new()
  256. {
  257. EventType = WindowsConsole.EventType.Key,
  258. KeyEvent = new()
  259. {
  260. bKeyDown = false,
  261. wRepeatCount = 0,
  262. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  263. wVirtualScanCode = 0,
  264. UnicodeChar = '\0',
  265. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  266. }
  267. });
  268. WaitIteration ();
  269. return this;
  270. }
  271. public GuiTestContext WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  272. {
  273. LastView.MouseEvent += (s, e) =>
  274. {
  275. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  276. {
  277. ctx.Show (menuItems);
  278. }
  279. };
  280. return this;
  281. }
  282. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  283. }