ApplicationV2Tests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Runtime.CompilerServices;
  4. using Microsoft.Extensions.Logging;
  5. using Moq;
  6. namespace UnitTests.ConsoleDrivers.V2;
  7. public class ApplicationV2Tests
  8. {
  9. private ApplicationV2 NewApplicationV2 ()
  10. {
  11. var netInput = new Mock<INetInput> ();
  12. SetupRunInputMockMethodToBlock (netInput);
  13. var winInput = new Mock<IWindowsInput> ();
  14. SetupRunInputMockMethodToBlock (winInput);
  15. return new (
  16. () => netInput.Object,
  17. Mock.Of<IConsoleOutput>,
  18. () => winInput.Object,
  19. Mock.Of<IConsoleOutput>);
  20. }
  21. [Fact]
  22. public void Init_CreatesKeybindings ()
  23. {
  24. var orig = ApplicationImpl.Instance;
  25. var v2 = NewApplicationV2 ();
  26. ApplicationImpl.ChangeInstance (v2);
  27. Application.KeyBindings.Clear ();
  28. Assert.Empty (Application.KeyBindings.GetBindings ());
  29. v2.Init ();
  30. Assert.NotEmpty (Application.KeyBindings.GetBindings ());
  31. v2.Shutdown ();
  32. ApplicationImpl.ChangeInstance (orig);
  33. }
  34. [Fact]
  35. public void Init_DriverIsFacade ()
  36. {
  37. var orig = ApplicationImpl.Instance;
  38. var v2 = NewApplicationV2 ();
  39. ApplicationImpl.ChangeInstance (v2);
  40. Assert.Null (Application.Driver);
  41. v2.Init ();
  42. Assert.NotNull (Application.Driver);
  43. var type = Application.Driver.GetType ();
  44. Assert.True (type.IsGenericType);
  45. Assert.True (type.GetGenericTypeDefinition () == typeof (ConsoleDriverFacade<>));
  46. v2.Shutdown ();
  47. Assert.Null (Application.Driver);
  48. ApplicationImpl.ChangeInstance (orig);
  49. }
  50. [Fact]
  51. public void Init_ExplicitlyRequestWin ()
  52. {
  53. var orig = ApplicationImpl.Instance;
  54. Assert.Null (Application.Driver);
  55. var netInput = new Mock<INetInput> (MockBehavior.Strict);
  56. var netOutput = new Mock<IConsoleOutput> (MockBehavior.Strict);
  57. var winInput = new Mock<IWindowsInput> (MockBehavior.Strict);
  58. var winOutput = new Mock<IConsoleOutput> (MockBehavior.Strict);
  59. winInput.Setup (i => i.Initialize (It.IsAny<ConcurrentQueue<WindowsConsole.InputRecord>> ()))
  60. .Verifiable (Times.Once);
  61. SetupRunInputMockMethodToBlock (winInput);
  62. winInput.Setup (i => i.Dispose ())
  63. .Verifiable (Times.Once);
  64. winOutput.Setup (i => i.Dispose ())
  65. .Verifiable (Times.Once);
  66. var v2 = new ApplicationV2 (
  67. () => netInput.Object,
  68. () => netOutput.Object,
  69. () => winInput.Object,
  70. () => winOutput.Object);
  71. ApplicationImpl.ChangeInstance (v2);
  72. Assert.Null (Application.Driver);
  73. v2.Init (null, "v2win");
  74. Assert.NotNull (Application.Driver);
  75. var type = Application.Driver.GetType ();
  76. Assert.True (type.IsGenericType);
  77. Assert.True (type.GetGenericTypeDefinition () == typeof (ConsoleDriverFacade<>));
  78. v2.Shutdown ();
  79. Assert.Null (Application.Driver);
  80. winInput.VerifyAll ();
  81. ApplicationImpl.ChangeInstance (orig);
  82. }
  83. [Fact]
  84. public void Init_ExplicitlyRequestNet ()
  85. {
  86. var orig = ApplicationImpl.Instance;
  87. var netInput = new Mock<INetInput> (MockBehavior.Strict);
  88. var netOutput = new Mock<IConsoleOutput> (MockBehavior.Strict);
  89. var winInput = new Mock<IWindowsInput> (MockBehavior.Strict);
  90. var winOutput = new Mock<IConsoleOutput> (MockBehavior.Strict);
  91. netInput.Setup (i => i.Initialize (It.IsAny<ConcurrentQueue<ConsoleKeyInfo>> ()))
  92. .Verifiable (Times.Once);
  93. SetupRunInputMockMethodToBlock (netInput);
  94. netInput.Setup (i => i.Dispose ())
  95. .Verifiable (Times.Once);
  96. netOutput.Setup (i => i.Dispose ())
  97. .Verifiable (Times.Once);
  98. var v2 = new ApplicationV2 (
  99. () => netInput.Object,
  100. () => netOutput.Object,
  101. () => winInput.Object,
  102. () => winOutput.Object);
  103. ApplicationImpl.ChangeInstance (v2);
  104. Assert.Null (Application.Driver);
  105. v2.Init (null, "v2net");
  106. Assert.NotNull (Application.Driver);
  107. var type = Application.Driver.GetType ();
  108. Assert.True (type.IsGenericType);
  109. Assert.True (type.GetGenericTypeDefinition () == typeof (ConsoleDriverFacade<>));
  110. v2.Shutdown ();
  111. Assert.Null (Application.Driver);
  112. netInput.VerifyAll ();
  113. ApplicationImpl.ChangeInstance (orig);
  114. }
  115. private void SetupRunInputMockMethodToBlock (Mock<IWindowsInput> winInput)
  116. {
  117. winInput.Setup (r => r.Run (It.IsAny<CancellationToken> ()))
  118. .Callback<CancellationToken> (token =>
  119. {
  120. // Simulate an infinite loop that checks for cancellation
  121. while (!token.IsCancellationRequested)
  122. {
  123. // Perform the action that should repeat in the loop
  124. // This could be some mock behavior or just an empty loop depending on the context
  125. }
  126. })
  127. .Verifiable (Times.Once);
  128. }
  129. private void SetupRunInputMockMethodToBlock (Mock<INetInput> netInput)
  130. {
  131. netInput.Setup (r => r.Run (It.IsAny<CancellationToken> ()))
  132. .Callback<CancellationToken> (token =>
  133. {
  134. // Simulate an infinite loop that checks for cancellation
  135. while (!token.IsCancellationRequested)
  136. {
  137. // Perform the action that should repeat in the loop
  138. // This could be some mock behavior or just an empty loop depending on the context
  139. }
  140. })
  141. .Verifiable (Times.Once);
  142. }
  143. [Fact]
  144. public void NoInitThrowOnRun ()
  145. {
  146. var orig = ApplicationImpl.Instance;
  147. Assert.Null (Application.Driver);
  148. var app = NewApplicationV2 ();
  149. ApplicationImpl.ChangeInstance (app);
  150. var ex = Assert.Throws<NotInitializedException> (() => app.Run (new Window ()));
  151. Assert.Equal ("Run cannot be accessed before Initialization", ex.Message);
  152. app.Shutdown();
  153. ApplicationImpl.ChangeInstance (orig);
  154. }
  155. [Fact]
  156. public void InitRunShutdown_Top_Set_To_Null_After_Shutdown ()
  157. {
  158. var orig = ApplicationImpl.Instance;
  159. var v2 = NewApplicationV2 ();
  160. ApplicationImpl.ChangeInstance (v2);
  161. v2.Init ();
  162. var timeoutToken = v2.AddTimeout (TimeSpan.FromMilliseconds (150),
  163. () =>
  164. {
  165. if (Application.Top != null)
  166. {
  167. Application.RequestStop ();
  168. return false;
  169. }
  170. return false;
  171. }
  172. );
  173. Assert.Null (Application.Top);
  174. // Blocks until the timeout call is hit
  175. v2.Run (new Window ());
  176. // We returned false above, so we should not have to remove the timeout
  177. Assert.False(v2.RemoveTimeout (timeoutToken));
  178. Assert.NotNull (Application.Top);
  179. Application.Top?.Dispose ();
  180. v2.Shutdown ();
  181. Assert.Null (Application.Top);
  182. ApplicationImpl.ChangeInstance (orig);
  183. }
  184. [Fact]
  185. public void InitRunShutdown_Running_Set_To_False ()
  186. {
  187. var orig = ApplicationImpl.Instance;
  188. var v2 = NewApplicationV2 ();
  189. ApplicationImpl.ChangeInstance (v2);
  190. v2.Init ();
  191. Toplevel top = new Window ()
  192. {
  193. Title = "InitRunShutdown_Running_Set_To_False"
  194. };
  195. var timeoutToken = v2.AddTimeout (TimeSpan.FromMilliseconds (150),
  196. () =>
  197. {
  198. Assert.True (top!.Running);
  199. if (Application.Top != null)
  200. {
  201. Application.RequestStop ();
  202. return false;
  203. }
  204. return false;
  205. }
  206. );
  207. Assert.False (top!.Running);
  208. // Blocks until the timeout call is hit
  209. v2.Run (top);
  210. // We returned false above, so we should not have to remove the timeout
  211. Assert.False (v2.RemoveTimeout (timeoutToken));
  212. Assert.False (top!.Running);
  213. // BUGBUG: Shutdown sets Top to null, not End.
  214. //Assert.Null (Application.Top);
  215. Application.Top?.Dispose ();
  216. v2.Shutdown ();
  217. ApplicationImpl.ChangeInstance (orig);
  218. }
  219. [Fact]
  220. public void InitRunShutdown_End_Is_Called ()
  221. {
  222. var orig = ApplicationImpl.Instance;
  223. var v2 = NewApplicationV2 ();
  224. ApplicationImpl.ChangeInstance (v2);
  225. Assert.Null (Application.Top);
  226. Assert.Null (Application.Driver);
  227. v2.Init ();
  228. Toplevel top = new Window ();
  229. // BUGBUG: Both Closed and Unloaded are called from End; what's the difference?
  230. int closedCount = 0;
  231. top.Closed
  232. += (_, a) =>
  233. {
  234. closedCount++;
  235. };
  236. int unloadedCount = 0;
  237. top.Unloaded
  238. += (_, a) =>
  239. {
  240. unloadedCount++;
  241. };
  242. var timeoutToken = v2.AddTimeout (TimeSpan.FromMilliseconds (150),
  243. () =>
  244. {
  245. Assert.True (top!.Running);
  246. if (Application.Top != null)
  247. {
  248. Application.RequestStop ();
  249. return false;
  250. }
  251. return false;
  252. }
  253. );
  254. Assert.Equal (0, closedCount);
  255. Assert.Equal (0, unloadedCount);
  256. // Blocks until the timeout call is hit
  257. v2.Run (top);
  258. Assert.Equal (1, closedCount);
  259. Assert.Equal (1, unloadedCount);
  260. // We returned false above, so we should not have to remove the timeout
  261. Assert.False (v2.RemoveTimeout (timeoutToken));
  262. Application.Top?.Dispose ();
  263. v2.Shutdown ();
  264. Assert.Equal (1, closedCount);
  265. Assert.Equal (1, unloadedCount);
  266. ApplicationImpl.ChangeInstance (orig);
  267. }
  268. [Fact]
  269. public void InitRunShutdown_QuitKey_Quits ()
  270. {
  271. var orig = ApplicationImpl.Instance;
  272. var v2 = NewApplicationV2 ();
  273. ApplicationImpl.ChangeInstance (v2);
  274. v2.Init ();
  275. Toplevel top = new Window ()
  276. {
  277. Title = "InitRunShutdown_QuitKey_Quits"
  278. };
  279. var timeoutToken = v2.AddTimeout (TimeSpan.FromMilliseconds (150),
  280. () =>
  281. {
  282. Assert.True (top!.Running);
  283. if (Application.Top != null)
  284. {
  285. Application.RaiseKeyDownEvent (Application.QuitKey);
  286. return false;
  287. }
  288. return false;
  289. }
  290. );
  291. Assert.False (top!.Running);
  292. // Blocks until the timeout call is hit
  293. v2.Run (top);
  294. // We returned false above, so we should not have to remove the timeout
  295. Assert.False (v2.RemoveTimeout (timeoutToken));
  296. Assert.False (top!.Running);
  297. Assert.NotNull (Application.Top);
  298. top.Dispose ();
  299. v2.Shutdown ();
  300. Assert.Null (Application.Top);
  301. ApplicationImpl.ChangeInstance (orig);
  302. }
  303. [Fact]
  304. public void InitRunShutdown_Generic_IdleForExit ()
  305. {
  306. var orig = ApplicationImpl.Instance;
  307. var v2 = NewApplicationV2 ();
  308. ApplicationImpl.ChangeInstance (v2);
  309. v2.Init ();
  310. v2.AddIdle (IdleExit);
  311. Assert.Null (Application.Top);
  312. // Blocks until the timeout call is hit
  313. v2.Run<Window> ();
  314. Assert.NotNull (Application.Top);
  315. Application.Top?.Dispose ();
  316. v2.Shutdown ();
  317. Assert.Null (Application.Top);
  318. ApplicationImpl.ChangeInstance (orig);
  319. }
  320. [Fact]
  321. public void Shutdown_Closing_Closed_Raised ()
  322. {
  323. var orig = ApplicationImpl.Instance;
  324. var v2 = NewApplicationV2 ();
  325. ApplicationImpl.ChangeInstance (v2);
  326. v2.Init ();
  327. int closing = 0;
  328. int closed = 0;
  329. var t = new Toplevel ();
  330. t.Closing
  331. += (_, a) =>
  332. {
  333. // Cancel the first time
  334. if (closing == 0)
  335. {
  336. a.Cancel = true;
  337. }
  338. closing++;
  339. Assert.Same (t, a.RequestingTop);
  340. };
  341. t.Closed
  342. += (_, a) =>
  343. {
  344. closed++;
  345. Assert.Same (t, a.Toplevel);
  346. };
  347. v2.AddIdle (IdleExit);
  348. // Blocks until the timeout call is hit
  349. v2.Run (t);
  350. Application.Top?.Dispose ();
  351. v2.Shutdown ();
  352. ApplicationImpl.ChangeInstance (orig);
  353. Assert.Equal (2, closing);
  354. Assert.Equal (1, closed);
  355. }
  356. private bool IdleExit ()
  357. {
  358. if (Application.Top != null)
  359. {
  360. Application.RequestStop ();
  361. return true;
  362. }
  363. return true;
  364. }
  365. [Fact]
  366. public void Shutdown_Called_Repeatedly_DoNotDuplicateDisposeOutput ()
  367. {
  368. var orig = ApplicationImpl.Instance;
  369. var netInput = new Mock<INetInput> ();
  370. SetupRunInputMockMethodToBlock (netInput);
  371. Mock<IConsoleOutput>? outputMock = null;
  372. var v2 = new ApplicationV2 (
  373. () => netInput.Object,
  374. () => (outputMock = new Mock<IConsoleOutput> ()).Object,
  375. Mock.Of<IWindowsInput>,
  376. Mock.Of<IConsoleOutput>);
  377. ApplicationImpl.ChangeInstance (v2);
  378. v2.Init (null, "v2net");
  379. v2.Shutdown ();
  380. v2.Shutdown ();
  381. outputMock!.Verify (o => o.Dispose (), Times.Once);
  382. ApplicationImpl.ChangeInstance (orig);
  383. }
  384. [Fact]
  385. public void Init_Called_Repeatedly_WarnsAndIgnores ()
  386. {
  387. var orig = ApplicationImpl.Instance;
  388. var v2 = NewApplicationV2 ();
  389. ApplicationImpl.ChangeInstance (v2);
  390. Assert.Null (Application.Driver);
  391. v2.Init ();
  392. Assert.NotNull (Application.Driver);
  393. var mockLogger = new Mock<ILogger> ();
  394. var beforeLogger = Logging.Logger;
  395. Logging.Logger = mockLogger.Object;
  396. v2.Init ();
  397. v2.Init ();
  398. mockLogger.Verify (
  399. l => l.Log (LogLevel.Error,
  400. It.IsAny<EventId> (),
  401. It.Is<It.IsAnyType> ((v, t) => v.ToString () == "Init called multiple times without shutdown, ignoring."),
  402. It.IsAny<Exception> (),
  403. It.IsAny<Func<It.IsAnyType, Exception, string>> ()!)
  404. , Times.Exactly (2));
  405. v2.Shutdown ();
  406. // Restore the original null logger to be polite to other tests
  407. Logging.Logger = beforeLogger;
  408. ApplicationImpl.ChangeInstance (orig);
  409. }
  410. [Fact]
  411. public void Open_Calls_ContinueWith_On_UIThread ()
  412. {
  413. var orig = ApplicationImpl.Instance;
  414. var v2 = NewApplicationV2 ();
  415. ApplicationImpl.ChangeInstance (v2);
  416. v2.Init ();
  417. var b = new Button ();
  418. bool result = false;
  419. b.Accepting +=
  420. (_, _) =>
  421. {
  422. Task.Run (() =>
  423. {
  424. Task.Delay (300).Wait ();
  425. }).ContinueWith (
  426. (t, _) =>
  427. {
  428. // no longer loading
  429. Application.Invoke (() =>
  430. {
  431. result = true;
  432. Application.RequestStop ();
  433. });
  434. },
  435. TaskScheduler.FromCurrentSynchronizationContext ());
  436. };
  437. v2.AddTimeout (TimeSpan.FromMilliseconds (150),
  438. () =>
  439. {
  440. // Run asynchronous logic inside Task.Run
  441. if (Application.Top != null)
  442. {
  443. b.NewKeyDownEvent (Key.Enter);
  444. b.NewKeyUpEvent (Key.Enter);
  445. return false;
  446. }
  447. return false;
  448. });
  449. Assert.Null (Application.Top);
  450. var w = new Window ()
  451. {
  452. Title = "Open_CallsContinueWithOnUIThread"
  453. };
  454. w.Add (b);
  455. // Blocks until the timeout call is hit
  456. v2.Run (w);
  457. Assert.NotNull (Application.Top);
  458. Application.Top?.Dispose ();
  459. v2.Shutdown ();
  460. Assert.Null (Application.Top);
  461. ApplicationImpl.ChangeInstance (orig);
  462. Assert.True (result);
  463. }
  464. }