MainLoopTests.cs 30 KB

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