MainLoopTests.cs 28 KB

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