MainLoopTests.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. using System.Diagnostics;
  2. using Xunit.Abstractions;
  3. // Alias Console to MockConsole so we don't accidentally use Console
  4. namespace UnitTests.ApplicationTests;
  5. /// <summary>Tests MainLoop using the FakeMainLoop.</summary>
  6. public class MainLoopTests
  7. {
  8. private readonly ITestOutputHelper _output;
  9. public MainLoopTests (ITestOutputHelper output)
  10. {
  11. _output = output;
  12. ConsoleDriver.RunningUnitTests = true;
  13. }
  14. private static Button btn;
  15. private static string cancel;
  16. private static string clickMe;
  17. private static int four;
  18. private static int one;
  19. private static string pewPew;
  20. private static bool taskCompleted;
  21. // TODO: EventsPending tests
  22. // - wait = true
  23. // - wait = false
  24. // TODO: Add IMainLoop tests
  25. private static int three;
  26. private static int total;
  27. private static int two;
  28. private static int zero;
  29. // See Also ConsoleDRivers/MainLoopDriverTests.cs for tests of the MainLoopDriver
  30. // Idle Handler tests
  31. [Fact]
  32. public void AddTimeout_Adds_And_Removes ()
  33. {
  34. var ml = new MainLoop (new FakeMainLoop ());
  35. Func<bool> fnTrue = () => true;
  36. Func<bool> fnFalse = () => false;
  37. var a = ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
  38. var b = ml.TimedEvents.Add (TimeSpan.Zero, fnFalse);
  39. Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
  40. Assert.Equal (fnTrue, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
  41. Assert.NotEqual (fnFalse, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
  42. Assert.True (ml.TimedEvents.Remove (a));
  43. Assert.Single (ml.TimedEvents.Timeouts);
  44. // BUGBUG: This doesn't throw or indicate an error. Ideally RemoveIdle would either
  45. // throw an exception in this case, or return an error.
  46. // No. Only need to return a boolean.
  47. Assert.False (ml.TimedEvents.Remove (a));
  48. Assert.True (ml.TimedEvents.Remove (b));
  49. // BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either
  50. // throw an exception in this case, or return an error.
  51. // No. Only need to return a boolean.
  52. Assert.False (ml.TimedEvents.Remove(b));
  53. }
  54. [Fact]
  55. public void AddTimeout_Function_GetsCalled_OnIteration ()
  56. {
  57. var ml = new MainLoop (new FakeMainLoop ());
  58. var functionCalled = 0;
  59. Func<bool> fn = () =>
  60. {
  61. functionCalled++;
  62. return true;
  63. };
  64. ml.TimedEvents.Add (TimeSpan.Zero, fn);
  65. ml.RunIteration ();
  66. Assert.Equal (1, functionCalled);
  67. }
  68. [Fact]
  69. public void AddTimeout_Twice_Returns_False_Called_Twice ()
  70. {
  71. var ml = new MainLoop (new FakeMainLoop ());
  72. var functionCalled = 0;
  73. Func<bool> fn1 = () =>
  74. {
  75. functionCalled++;
  76. return false;
  77. };
  78. // Force stop if 10 iterations
  79. var stopCount = 0;
  80. Func<bool> fnStop = () =>
  81. {
  82. stopCount++;
  83. if (stopCount == 10)
  84. {
  85. ml.Stop ();
  86. }
  87. return true;
  88. };
  89. var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
  90. var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
  91. ml.Run ();
  92. Assert.True (ml.TimedEvents.Remove(a));
  93. Assert.False (ml.TimedEvents.Remove (a));
  94. // Cannot remove b because it returned false i.e. auto removes itself
  95. Assert.False (ml.TimedEvents.Remove (b));
  96. Assert.Equal (1, functionCalled);
  97. }
  98. [Fact]
  99. public void AddTimeoutTwice_Function_CalledTwice ()
  100. {
  101. var ml = new MainLoop (new FakeMainLoop ());
  102. var functionCalled = 0;
  103. Func<bool> fn = () =>
  104. {
  105. functionCalled++;
  106. return true;
  107. };
  108. var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
  109. var b = ml.TimedEvents.Add (TimeSpan.Zero, fn);
  110. ml.RunIteration ();
  111. Assert.Equal (2, functionCalled);
  112. Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
  113. functionCalled = 0;
  114. Assert.True (ml.TimedEvents.Remove (a));
  115. Assert.Single (ml.TimedEvents.Timeouts);
  116. ml.RunIteration ();
  117. Assert.Equal (1, functionCalled);
  118. functionCalled = 0;
  119. Assert.True (ml.TimedEvents.Remove (b));
  120. Assert.Empty (ml.TimedEvents.Timeouts);
  121. ml.RunIteration ();
  122. Assert.Equal (0, functionCalled);
  123. Assert.False (ml.TimedEvents.Remove (b));
  124. }
  125. [Fact]
  126. public void AddThenRemoveIdle_Function_NotCalled ()
  127. {
  128. var ml = new MainLoop (new FakeMainLoop ());
  129. var functionCalled = 0;
  130. Func<bool> fn = () =>
  131. {
  132. functionCalled++;
  133. return true;
  134. };
  135. var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
  136. Assert.True (ml.TimedEvents.Remove (a));
  137. ml.RunIteration ();
  138. Assert.Equal (0, functionCalled);
  139. }
  140. // Timeout Handler Tests
  141. [Fact]
  142. public void AddTimer_Adds_Removes_NoFaults ()
  143. {
  144. var ml = new MainLoop (new FakeMainLoop ());
  145. var ms = 100;
  146. var callbackCount = 0;
  147. Func<bool> callback = () =>
  148. {
  149. callbackCount++;
  150. return true;
  151. };
  152. object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
  153. Assert.True (ml.TimedEvents.Remove (token));
  154. // BUGBUG: This should probably fault?
  155. // Must return a boolean.
  156. Assert.False (ml.TimedEvents.Remove (token));
  157. }
  158. [Fact]
  159. public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
  160. {
  161. var ml = new MainLoop (new FakeMainLoop ());
  162. const int ms = 100;
  163. object token1 = null, token2 = null;
  164. var callbackCount = 0;
  165. Func<bool> callback = () =>
  166. {
  167. callbackCount++;
  168. if (callbackCount == 2)
  169. {
  170. ml.Stop ();
  171. }
  172. return true;
  173. };
  174. var task1 = new Task (() => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
  175. var task2 = new Task (() => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
  176. Assert.Null (token1);
  177. Assert.Null (token2);
  178. task1.Start ();
  179. task2.Start ();
  180. ml.Run ();
  181. Assert.NotNull (token1);
  182. Assert.NotNull (token2);
  183. await Task.WhenAll (task1, task2);
  184. Assert.True (ml.TimedEvents.Remove (token1));
  185. Assert.True (ml.TimedEvents.Remove (token2));
  186. Assert.Equal (2, callbackCount);
  187. }
  188. // Timeout Handler Tests
  189. [Fact]
  190. public void AddTimer_EventFired ()
  191. {
  192. var ml = new MainLoop (new FakeMainLoop ());
  193. var ms = 100;
  194. // Use Stopwatch ticks since TimedEvents now uses Stopwatch.GetTimestamp internally
  195. long originTicks = Stopwatch.GetTimestamp () * TimeSpan.TicksPerSecond / Stopwatch.Frequency;
  196. var callbackCount = 0;
  197. Func<bool> callback = () =>
  198. {
  199. callbackCount++;
  200. return true;
  201. };
  202. object sender = null;
  203. TimeoutEventArgs args = null;
  204. ml.TimedEvents.Added += (s, e) =>
  205. {
  206. sender = s;
  207. args = e;
  208. };
  209. object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
  210. Assert.Same (ml.TimedEvents, sender);
  211. Assert.NotNull (args.Timeout);
  212. Assert.True (args.Ticks - originTicks >= 100 * TimeSpan.TicksPerMillisecond);
  213. }
  214. [Fact]
  215. public void AddTimer_In_Parallel_Wont_Throw ()
  216. {
  217. var ml = new MainLoop (new FakeMainLoop ());
  218. const int ms = 100;
  219. object token1 = null, token2 = null;
  220. var callbackCount = 0;
  221. Func<bool> callback = () =>
  222. {
  223. callbackCount++;
  224. if (callbackCount == 2)
  225. {
  226. ml.Stop ();
  227. }
  228. return true;
  229. };
  230. Parallel.Invoke (
  231. () => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback),
  232. () => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback)
  233. );
  234. ml.Run ();
  235. Assert.NotNull (token1);
  236. Assert.NotNull (token2);
  237. Assert.True (ml.TimedEvents.Remove (token1));
  238. Assert.True (ml.TimedEvents.Remove (token2));
  239. Assert.Equal (2, callbackCount);
  240. }
  241. [Fact]
  242. public void AddTimer_Remove_NotCalled ()
  243. {
  244. var ml = new MainLoop (new FakeMainLoop ());
  245. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  246. // Force stop if 10 iterations
  247. var stopCount = 0;
  248. Func<bool> fnStop = () =>
  249. {
  250. stopCount++;
  251. if (stopCount == 10)
  252. {
  253. ml.Stop ();
  254. }
  255. return true;
  256. };
  257. ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
  258. var callbackCount = 0;
  259. Func<bool> callback = () =>
  260. {
  261. callbackCount++;
  262. return true;
  263. };
  264. object token = ml.TimedEvents.Add (ms, callback);
  265. Assert.True (ml.TimedEvents.Remove (token));
  266. ml.Run ();
  267. Assert.Equal (0, callbackCount);
  268. }
  269. [Fact]
  270. public void AddTimer_ReturnFalse_StopsBeingCalled ()
  271. {
  272. var ml = new MainLoop (new FakeMainLoop ());
  273. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  274. // Force stop if 10 iterations
  275. var stopCount = 0;
  276. Func<bool> fnStop = () =>
  277. {
  278. Thread.Sleep (10); // Sleep to enable timer to fire
  279. stopCount++;
  280. if (stopCount == 10)
  281. {
  282. ml.Stop ();
  283. }
  284. return true;
  285. };
  286. ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
  287. var callbackCount = 0;
  288. Func<bool> callback = () =>
  289. {
  290. callbackCount++;
  291. return false;
  292. };
  293. object token = ml.TimedEvents.Add (ms, callback);
  294. ml.Run ();
  295. Assert.Equal (1, callbackCount);
  296. Assert.Equal (10, stopCount);
  297. Assert.False (ml.TimedEvents.Remove (token));
  298. }
  299. [Fact]
  300. public void AddTimer_Run_Called ()
  301. {
  302. var ml = new MainLoop (new FakeMainLoop ());
  303. var ms = 100;
  304. var callbackCount = 0;
  305. Func<bool> callback = () =>
  306. {
  307. callbackCount++;
  308. ml.Stop ();
  309. return true;
  310. };
  311. object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
  312. ml.Run ();
  313. Assert.True (ml.TimedEvents.Remove (token));
  314. Assert.Equal (1, callbackCount);
  315. }
  316. [Fact]
  317. public void AddTimer_Run_CalledAtApproximatelyRightTime ()
  318. {
  319. var ml = new MainLoop (new FakeMainLoop ());
  320. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  321. var watch = new Stopwatch ();
  322. var callbackCount = 0;
  323. Func<bool> callback = () =>
  324. {
  325. watch.Stop ();
  326. callbackCount++;
  327. ml.Stop ();
  328. return true;
  329. };
  330. object token = ml.TimedEvents.Add (ms, callback);
  331. watch.Start ();
  332. ml.Run ();
  333. // +/- 100ms should be good enuf
  334. // https://github.com/xunit/assert.xunit/pull/25
  335. Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  336. Assert.True (ml.TimedEvents.Remove (token));
  337. Assert.Equal (1, callbackCount);
  338. }
  339. [Fact]
  340. public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
  341. {
  342. var ml = new MainLoop (new FakeMainLoop ());
  343. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  344. var watch = new Stopwatch ();
  345. var callbackCount = 0;
  346. Func<bool> callback = () =>
  347. {
  348. callbackCount++;
  349. if (callbackCount == 2)
  350. {
  351. watch.Stop ();
  352. ml.Stop ();
  353. }
  354. return true;
  355. };
  356. object token = ml.TimedEvents.Add (ms, callback);
  357. watch.Start ();
  358. ml.Run ();
  359. // +/- 100ms should be good enuf
  360. // https://github.com/xunit/assert.xunit/pull/25
  361. Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  362. Assert.True (ml.TimedEvents.Remove (token));
  363. Assert.Equal (2, callbackCount);
  364. }
  365. [Fact]
  366. public void CheckTimersAndIdleHandlers_NoTimers_Returns_False ()
  367. {
  368. var ml = new MainLoop (new FakeMainLoop ());
  369. bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
  370. Assert.False (retVal);
  371. Assert.Equal (-1, waitTimeOut);
  372. }
  373. [Fact]
  374. public void CheckTimersAndIdleHandlers_NoTimers_WithIdle_Returns_True ()
  375. {
  376. var ml = new MainLoop (new FakeMainLoop ());
  377. Func<bool> fnTrue = () => true;
  378. ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
  379. bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
  380. Assert.True (retVal);
  381. Assert.Equal (0, waitTimeOut);
  382. }
  383. [Fact]
  384. public void CheckTimersAndIdleHandlers_With1Timer_Returns_Timer ()
  385. {
  386. var ml = new MainLoop (new FakeMainLoop ());
  387. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  388. static bool Callback () { return false; }
  389. _ = ml.TimedEvents.Add (ms, Callback);
  390. bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
  391. Assert.True (retVal);
  392. // It should take < 10ms to execute to here
  393. Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
  394. }
  395. [Fact]
  396. public void CheckTimersAndIdleHandlers_With2Timers_Returns_Timer ()
  397. {
  398. var ml = new MainLoop (new FakeMainLoop ());
  399. TimeSpan ms = TimeSpan.FromMilliseconds (50);
  400. static bool Callback () { return false; }
  401. _ = ml.TimedEvents.Add (ms, Callback);
  402. _ = ml.TimedEvents.Add (ms, Callback);
  403. bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
  404. Assert.True (retVal);
  405. // It should take < 10ms to execute to here
  406. Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
  407. }
  408. [Fact]
  409. public void False_Idle_Stops_It_Being_Called_Again ()
  410. {
  411. var ml = new MainLoop (new FakeMainLoop ());
  412. var functionCalled = 0;
  413. Func<bool> fn1 = () =>
  414. {
  415. functionCalled++;
  416. if (functionCalled == 10)
  417. {
  418. return false;
  419. }
  420. return true;
  421. };
  422. // Force stop if 20 iterations
  423. var stopCount = 0;
  424. Func<bool> fnStop = () =>
  425. {
  426. stopCount++;
  427. if (stopCount == 20)
  428. {
  429. ml.Stop ();
  430. }
  431. return true;
  432. };
  433. var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
  434. var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
  435. ml.Run ();
  436. Assert.True (ml.TimedEvents.Remove (a));
  437. Assert.False (ml.TimedEvents.Remove (a));
  438. Assert.Equal (10, functionCalled);
  439. Assert.Equal (20, stopCount);
  440. }
  441. [Fact]
  442. public void Internal_Tests ()
  443. {
  444. var testMainloop = new TestMainloop ();
  445. var mainloop = new MainLoop (testMainloop);
  446. Assert.Empty (mainloop.TimedEvents.Timeouts);
  447. Assert.NotNull (
  448. new Terminal.Gui.App.Timeout { Span = new (), Callback = () => true }
  449. );
  450. }
  451. [Theory]
  452. [MemberData (nameof (TestAddTimeout))]
  453. public void Mainloop_Invoke_Or_AddTimeout_Can_Be_Used_For_Events_Or_Actions (
  454. Action action,
  455. string pclickMe,
  456. string pcancel,
  457. string ppewPew,
  458. int pzero,
  459. int pone,
  460. int ptwo,
  461. int pthree,
  462. int pfour
  463. )
  464. {
  465. // TODO: Expand this test to test all drivers
  466. Application.Init (null, "fakedriver");
  467. total = 0;
  468. btn = null;
  469. clickMe = pclickMe;
  470. cancel = pcancel;
  471. pewPew = ppewPew;
  472. zero = pzero;
  473. one = pone;
  474. two = ptwo;
  475. three = pthree;
  476. four = pfour;
  477. taskCompleted = false;
  478. var btnLaunch = new Button { Text = "Open Window" };
  479. btnLaunch.Accepting += (s, e) => action ();
  480. var top = new Toplevel ();
  481. top.Add (btnLaunch);
  482. int iterations = -1;
  483. Application.Iteration += (s, a) =>
  484. {
  485. iterations++;
  486. if (iterations == 0)
  487. {
  488. Assert.Null (btn);
  489. Assert.Equal (zero, total);
  490. Assert.False (btnLaunch.NewKeyDownEvent (Key.Space));
  491. if (btn == null)
  492. {
  493. Assert.Null (btn);
  494. Assert.Equal (zero, total);
  495. }
  496. else
  497. {
  498. Assert.Equal (clickMe, btn.Text);
  499. Assert.Equal (four, total);
  500. }
  501. }
  502. else if (iterations == 1)
  503. {
  504. Assert.Equal (clickMe, btn.Text);
  505. Assert.Equal (zero, total);
  506. Assert.False (btn.NewKeyDownEvent (Key.Space));
  507. Assert.Equal (cancel, btn.Text);
  508. Assert.Equal (one, total);
  509. }
  510. else if (taskCompleted)
  511. {
  512. Application.RequestStop ();
  513. }
  514. };
  515. Application.Run (top);
  516. top.Dispose ();
  517. Assert.True (taskCompleted);
  518. Assert.Equal (clickMe, btn.Text);
  519. Assert.Equal (four, total);
  520. Application.Shutdown ();
  521. }
  522. [Fact]
  523. public void RemoveIdle_Function_NotCalled ()
  524. {
  525. var ml = new MainLoop (new FakeMainLoop ());
  526. var functionCalled = 0;
  527. Func<bool> fn = () =>
  528. {
  529. functionCalled++;
  530. return true;
  531. };
  532. Assert.False (ml.TimedEvents.Remove ("flibble"));
  533. ml.RunIteration ();
  534. Assert.Equal (0, functionCalled);
  535. }
  536. [Fact]
  537. public void Run_Runs_Idle_Stop_Stops_Idle ()
  538. {
  539. var ml = new MainLoop (new FakeMainLoop ());
  540. var functionCalled = 0;
  541. Func<bool> fn = () =>
  542. {
  543. functionCalled++;
  544. if (functionCalled == 10)
  545. {
  546. ml.Stop ();
  547. }
  548. return true;
  549. };
  550. var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
  551. ml.Run ();
  552. Assert.True (ml.TimedEvents.Remove (a));
  553. Assert.Equal (10, functionCalled);
  554. }
  555. [Theory]
  556. [InlineData ("fake")]
  557. [InlineData ("windows")]
  558. [InlineData ("dotnet")]
  559. [InlineData ("unix")]
  560. public void Application_Invoke_Run_TimedEvents (string driverName)
  561. {
  562. // Arrange
  563. Application.Init (driverName: driverName);
  564. var functionCalled = 0;
  565. var stopwatch = new Stopwatch ();
  566. // Act
  567. Application.Invoke (() =>
  568. {
  569. // Stop the stopwatch *after* the function is called.
  570. functionCalled++;
  571. stopwatch.Stop ();
  572. Application.RequestStop ();
  573. });
  574. // Start timing just before running the application loop.
  575. stopwatch.Start ();
  576. Application.Run ();
  577. // Assert
  578. Assert.NotNull (Application.Top);
  579. Application.Top.Dispose ();
  580. Application.Shutdown ();
  581. Assert.Equal (1, functionCalled);
  582. // Output the elapsed time for this test case.
  583. // ReSharper disable once Xunit.XunitTestWithConsoleOutput
  584. // ReSharper disable once LocalizableElement
  585. Console.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
  586. // Output elapsed duration to xUnit's test output
  587. _output.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
  588. }
  589. [Theory]
  590. [InlineData ("fake")]
  591. [InlineData ("windows")]
  592. [InlineData ("dotnet")]
  593. [InlineData ("unix")]
  594. public void Application_AddTimeout_Run_TimedEvents (string driverName)
  595. {
  596. // Arrange
  597. Application.Init (driverName: driverName);
  598. var functionCalled = 0;
  599. var stopwatch = new Stopwatch ();
  600. // Act
  601. bool Function ()
  602. {
  603. functionCalled++;
  604. if (functionCalled == 10 && Application.Top is { Running: true })
  605. {
  606. stopwatch.Stop ();
  607. Application.RequestStop ();
  608. return false;
  609. }
  610. return true;
  611. }
  612. Application.AddTimeout (TimeSpan.FromMilliseconds (1), Function);
  613. // Start timing just before running the application loop.
  614. stopwatch.Start ();
  615. Application.Run ();
  616. // Assert
  617. Assert.NotNull (Application.Top);
  618. Application.Top.Dispose ();
  619. Application.Shutdown ();
  620. Assert.Equal (10, functionCalled);
  621. // Output the elapsed time for this test case.
  622. // ReSharper disable once Xunit.XunitTestWithConsoleOutput
  623. // ReSharper disable once LocalizableElement
  624. Console.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
  625. // Output elapsed duration to xUnit's test output
  626. _output.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
  627. }
  628. public static IEnumerable<object []> TestAddTimeout
  629. {
  630. get
  631. {
  632. // Goes fine
  633. Action a1 = StartWindow;
  634. yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  635. // Also goes fine
  636. Action a2 = () => Application.Invoke (StartWindow);
  637. yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  638. }
  639. }
  640. private static async void RunAsyncTest (object sender, EventArgs e)
  641. {
  642. Assert.Equal (clickMe, btn.Text);
  643. Assert.Equal (zero, total);
  644. btn.Text = "Cancel";
  645. Interlocked.Increment (ref total);
  646. btn.SetNeedsDraw ();
  647. await Task.Run (
  648. () =>
  649. {
  650. try
  651. {
  652. Assert.Equal (cancel, btn.Text);
  653. Assert.Equal (one, total);
  654. RunSql ();
  655. }
  656. finally
  657. {
  658. SetReadyToRun ();
  659. }
  660. }
  661. )
  662. .ContinueWith (
  663. async (s, e) =>
  664. {
  665. await Task.Delay (1000);
  666. Assert.Equal (clickMe, btn.Text);
  667. Assert.Equal (three, total);
  668. Interlocked.Increment (ref total);
  669. Assert.Equal (clickMe, btn.Text);
  670. Assert.Equal (four, total);
  671. taskCompleted = true;
  672. },
  673. TaskScheduler.FromCurrentSynchronizationContext ()
  674. );
  675. }
  676. private static void RunSql ()
  677. {
  678. Thread.Sleep (100);
  679. Assert.Equal (cancel, btn.Text);
  680. Assert.Equal (one, total);
  681. Application.Invoke (
  682. () =>
  683. {
  684. btn.Text = "Pew Pew";
  685. Interlocked.Increment (ref total);
  686. btn.SetNeedsDraw ();
  687. }
  688. );
  689. }
  690. private static void SetReadyToRun ()
  691. {
  692. Thread.Sleep (100);
  693. Assert.Equal (pewPew, btn.Text);
  694. Assert.Equal (two, total);
  695. Application.Invoke (
  696. () =>
  697. {
  698. btn.Text = "Click Me";
  699. Interlocked.Increment (ref total);
  700. btn.SetNeedsDraw ();
  701. }
  702. );
  703. }
  704. private static void StartWindow ()
  705. {
  706. var startWindow = new Window { Modal = true };
  707. btn = new() { Text = "Click Me" };
  708. btn.Accepting += RunAsyncTest;
  709. var totalbtn = new Button { X = Pos.Right (btn), Text = "total" };
  710. totalbtn.Accepting += (s, e) => { MessageBox.Query ("Count", $"Count is {total}", "Ok"); };
  711. startWindow.Add (btn);
  712. startWindow.Add (totalbtn);
  713. Application.Run (startWindow);
  714. Assert.Equal (clickMe, btn.Text);
  715. Assert.Equal (four, total);
  716. Application.RequestStop ();
  717. }
  718. private class MillisecondTolerance : IEqualityComparer<TimeSpan>
  719. {
  720. public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
  721. private readonly int _tolerance;
  722. public bool Equals (TimeSpan x, TimeSpan y) { return Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance; }
  723. public int GetHashCode (TimeSpan obj) { return obj.GetHashCode (); }
  724. }
  725. private class TestMainloop : IMainLoopDriver
  726. {
  727. private MainLoop mainLoop;
  728. public bool EventsPending () { throw new NotImplementedException (); }
  729. public void Iteration () { throw new NotImplementedException (); }
  730. public void TearDown () { throw new NotImplementedException (); }
  731. public void Setup (MainLoop mainLoop) { this.mainLoop = mainLoop; }
  732. public void Wakeup () { throw new NotImplementedException (); }
  733. }
  734. }