MainLoopTests.cs 19 KB

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