StartAsyncTest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Linq;
  6. using System.Reactive;
  7. using System.Reactive.Concurrency;
  8. using System.Reactive.Linq;
  9. using System.Runtime.CompilerServices;
  10. using System.Security.Cryptography;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Microsoft.Reactive.Testing;
  14. using Microsoft.VisualStudio.TestTools.UnitTesting;
  15. using Tests.System.Reactive;
  16. using Assert = Xunit.Assert;
  17. namespace ReactiveTests.Tests
  18. {
  19. [TestClass]
  20. public class StartAsyncTest : ReactiveTest
  21. {
  22. private readonly Task<int> _doneTask;
  23. public StartAsyncTest()
  24. {
  25. var tcs = new TaskCompletionSource<int>();
  26. tcs.SetResult(42);
  27. _doneTask = tcs.Task;
  28. }
  29. #region Func
  30. [TestMethod]
  31. public void StartAsync_Func_ArgumentChecking()
  32. {
  33. var s = Scheduler.Immediate;
  34. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<Task<int>>)));
  35. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<CancellationToken, Task<int>>)));
  36. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<Task<int>>), s));
  37. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<CancellationToken, Task<int>>), s));
  38. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(() => _doneTask, default(IScheduler)));
  39. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(ct => _doneTask, default(IScheduler)));
  40. }
  41. [TestMethod]
  42. public void StartAsync_Func_Success()
  43. {
  44. var n = 42;
  45. var i = 0;
  46. var xs = Observable.StartAsync(() =>
  47. {
  48. i++;
  49. return Task.Factory.StartNew(() => n);
  50. });
  51. Assert.Equal(n, xs.Single());
  52. Assert.Equal(1, i);
  53. Assert.Equal(n, xs.Single());
  54. Assert.Equal(1, i);
  55. }
  56. [TestMethod]
  57. public void StartAsync_Func_Throw_Synchronous()
  58. {
  59. var ex = new Exception();
  60. var xs = Observable.StartAsync<int>(() =>
  61. {
  62. throw ex;
  63. });
  64. ReactiveAssert.Throws(ex, () => xs.Single());
  65. }
  66. [TestMethod]
  67. public void StartAsync_Func_Throw_Asynchronous()
  68. {
  69. var ex = new Exception();
  70. var xs = Observable.StartAsync(() =>
  71. Task.Factory.StartNew<int>(() =>
  72. {
  73. throw ex;
  74. })
  75. );
  76. ReactiveAssert.Throws(ex, () => xs.Single());
  77. }
  78. [TestMethod]
  79. public void StartAsync_FuncWithCancel_Success()
  80. {
  81. var n = 42;
  82. var i = 0;
  83. var xs = Observable.StartAsync(ct =>
  84. {
  85. i++;
  86. return Task.Factory.StartNew(() => n);
  87. });
  88. Assert.Equal(n, xs.Single());
  89. Assert.Equal(1, i);
  90. Assert.Equal(n, xs.Single());
  91. Assert.Equal(1, i);
  92. }
  93. [TestMethod]
  94. public void StartAsync_FuncWithCancel_Throw_Synchronous()
  95. {
  96. var ex = new Exception();
  97. var xs = Observable.StartAsync<int>(ct =>
  98. {
  99. throw ex;
  100. });
  101. ReactiveAssert.Throws(ex, () => xs.Single());
  102. }
  103. [TestMethod]
  104. public void StartAsync_FuncWithCancel_Throw_Asynchronous()
  105. {
  106. var ex = new Exception();
  107. var xs = Observable.StartAsync(ct =>
  108. Task.Factory.StartNew<int>(() => { throw ex; })
  109. );
  110. ReactiveAssert.Throws(ex, () => xs.Single());
  111. }
  112. [TestMethod]
  113. public void StartAsync_FuncWithCancel_Cancel()
  114. {
  115. var N = 10;
  116. for (var n = 0; n < N; n++)
  117. {
  118. var e = new ManualResetEvent(false);
  119. var f = new ManualResetEvent(false);
  120. var t = default(Task<int>);
  121. var xs = Observable.StartAsync(ct =>
  122. t = Task.Factory.StartNew<int>(() =>
  123. {
  124. try
  125. {
  126. e.Set();
  127. while (true)
  128. {
  129. ct.ThrowIfCancellationRequested();
  130. }
  131. }
  132. finally
  133. {
  134. f.Set();
  135. }
  136. })
  137. );
  138. e.WaitOne();
  139. var d = xs.Subscribe(_ => { });
  140. d.Dispose();
  141. f.WaitOne();
  142. while (!t.IsCompleted)
  143. {
  144. ;
  145. }
  146. ReactiveAssert.Throws<OperationCanceledException>(() => xs.Single());
  147. }
  148. }
  149. [TestMethod]
  150. public void Start_Func_UnsubscribeThenError_ErrorReportedAsUnobserved()
  151. {
  152. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  153. createTask => Observable.StartAsync(createTask),
  154. errorObservation =>
  155. {
  156. errorObservation.AssertExceptionReportedAsUnobserved();
  157. });
  158. }
  159. [TestMethod]
  160. public void Start_FuncWithCancel_UnsubscribeThenError_ErrorReportedAsUnobserved()
  161. {
  162. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  163. createTask => Observable.StartAsync(_ => createTask()),
  164. errorObservation =>
  165. {
  166. errorObservation.AssertExceptionReportedAsUnobserved();
  167. });
  168. }
  169. [TestMethod]
  170. public void Start_Func_WithScheduler_UnsubscribeThenError_ErrorReportedAsUnobserved()
  171. {
  172. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  173. createTask => Observable.StartAsync(createTask, TaskPoolScheduler.Default),
  174. errorObservation =>
  175. {
  176. errorObservation.AssertExceptionReportedAsUnobserved();
  177. });
  178. }
  179. [TestMethod]
  180. public void Start_FuncWithCancel_WithScheduler_UnsubscribeThenError_ErrorReportedAsUnobserved()
  181. {
  182. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  183. createTask => Observable.StartAsync(_ => createTask(), TaskPoolScheduler.Default),
  184. errorObservation =>
  185. {
  186. errorObservation.AssertExceptionReportedAsUnobserved();
  187. });
  188. }
  189. [TestMethod]
  190. public void Start_Func_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  191. {
  192. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  193. createTask => Observable.StartAsync(createTask, new TaskObservationOptions(null, ignoreExceptionsAfterUnsubscribe: true)),
  194. errorObservation =>
  195. {
  196. errorObservation.AssertExceptionNotReportedAsUnobserved();
  197. });
  198. }
  199. [TestMethod]
  200. public void Start_FuncWithCancel_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  201. {
  202. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  203. createTask => Observable.StartAsync(_ => createTask(), new TaskObservationOptions(null, ignoreExceptionsAfterUnsubscribe: true)),
  204. errorObservation =>
  205. {
  206. errorObservation.AssertExceptionNotReportedAsUnobserved();
  207. });
  208. }
  209. [TestMethod]
  210. public void Start_Func_WithScheduler_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  211. {
  212. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  213. createTask => Observable.StartAsync(createTask, new TaskObservationOptions(TaskPoolScheduler.Default, ignoreExceptionsAfterUnsubscribe: true)),
  214. errorObservation =>
  215. {
  216. errorObservation.AssertExceptionNotReportedAsUnobserved();
  217. });
  218. }
  219. [TestMethod]
  220. public void Start_FuncWithCancel_WithScheduler_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  221. {
  222. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  223. createTask => Observable.StartAsync(_ => createTask(), new TaskObservationOptions(TaskPoolScheduler.Default, ignoreExceptionsAfterUnsubscribe: true)),
  224. errorObservation =>
  225. {
  226. errorObservation.AssertExceptionNotReportedAsUnobserved();
  227. });
  228. }
  229. #if DESKTOPCLR
  230. [TestMethod]
  231. public void StartAsync_Func_Scheduler1()
  232. {
  233. var tcs = new TaskCompletionSource<int>();
  234. var e = new ManualResetEvent(false);
  235. var x = default(int);
  236. var t = default(int);
  237. var xs = Observable.StartAsync(() => tcs.Task, Scheduler.Immediate);
  238. xs.Subscribe(res =>
  239. {
  240. x = res;
  241. t = Environment.CurrentManagedThreadId;
  242. e.Set();
  243. });
  244. tcs.SetResult(42);
  245. e.WaitOne();
  246. Assert.Equal(42, x);
  247. Assert.Equal(Environment.CurrentManagedThreadId, t);
  248. }
  249. [TestMethod]
  250. public void StartAsync_Func_Scheduler2()
  251. {
  252. var tcs = new TaskCompletionSource<int>();
  253. var e = new ManualResetEvent(false);
  254. var x = default(int);
  255. var t = default(int);
  256. var xs = Observable.StartAsync(ct => tcs.Task, Scheduler.Immediate);
  257. xs.Subscribe(res =>
  258. {
  259. x = res;
  260. t = Environment.CurrentManagedThreadId;
  261. e.Set();
  262. });
  263. tcs.SetResult(42);
  264. e.WaitOne();
  265. Assert.Equal(42, x);
  266. Assert.Equal(Environment.CurrentManagedThreadId, t);
  267. }
  268. #endif
  269. #endregion
  270. #region Action
  271. [TestMethod]
  272. public void StartAsync_Action_ArgumentChecking()
  273. {
  274. var s = Scheduler.Immediate;
  275. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<Task>)));
  276. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<CancellationToken, Task>)));
  277. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<Task>), s));
  278. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(default(Func<CancellationToken, Task>), s));
  279. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(() => (Task)_doneTask, default(IScheduler)));
  280. ReactiveAssert.Throws<ArgumentNullException>(() => Observable.StartAsync(ct => (Task)_doneTask, default(IScheduler)));
  281. }
  282. [TestMethod]
  283. public void StartAsync_Action_Success()
  284. {
  285. var i = 0;
  286. var xs = Observable.StartAsync(() =>
  287. {
  288. i++;
  289. return Task.Factory.StartNew(() => { });
  290. });
  291. Assert.Equal(Unit.Default, xs.Single());
  292. Assert.Equal(1, i);
  293. Assert.Equal(Unit.Default, xs.Single());
  294. Assert.Equal(1, i);
  295. }
  296. [TestMethod]
  297. public void StartAsync_Action_Throw_Synchronous()
  298. {
  299. var ex = new Exception();
  300. var xs = Observable.StartAsync(() =>
  301. {
  302. throw ex;
  303. });
  304. ReactiveAssert.Throws(ex, () => xs.Single());
  305. }
  306. [TestMethod]
  307. public void StartAsync_Action_Throw_Asynchronous()
  308. {
  309. var ex = new Exception();
  310. var xs = Observable.StartAsync(() =>
  311. Task.Factory.StartNew(() => { throw ex; })
  312. );
  313. ReactiveAssert.Throws(ex, () => xs.Single());
  314. }
  315. [TestMethod]
  316. public void StartAsync_ActionWithCancel_Success()
  317. {
  318. var i = 0;
  319. var xs = Observable.StartAsync(ct =>
  320. {
  321. i++;
  322. return Task.Factory.StartNew(() => { }, CancellationToken.None); // Not forwarding ct because we always want this task to run to completion in this test.
  323. });
  324. Assert.Equal(Unit.Default, xs.Single());
  325. Assert.Equal(1, i);
  326. Assert.Equal(Unit.Default, xs.Single());
  327. Assert.Equal(1, i);
  328. }
  329. [TestMethod]
  330. public void StartAsync_ActionWithCancel_Throw_Synchronous()
  331. {
  332. var ex = new Exception();
  333. var xs = Observable.StartAsync(ct =>
  334. {
  335. throw ex;
  336. });
  337. ReactiveAssert.Throws(ex, () => xs.Single());
  338. }
  339. [TestMethod]
  340. public void StartAsync_ActionWithCancel_Throw_Asynchronous()
  341. {
  342. var ex = new Exception();
  343. var xs = Observable.StartAsync(ct =>
  344. Task.Factory.StartNew(() => { throw ex; }, CancellationToken.None) // Not forwarding ct because we always want this task to run and then fail in this test
  345. );
  346. ReactiveAssert.Throws(ex, () => xs.Single());
  347. }
  348. [TestMethod]
  349. public void StartAsync_ActionWithCancel_Cancel()
  350. {
  351. var N = 10;
  352. for (var n = 0; n < N; n++)
  353. {
  354. var e = new ManualResetEvent(false);
  355. var f = new ManualResetEvent(false);
  356. var t = default(Task);
  357. var xs = Observable.StartAsync(ct =>
  358. t = Task.Factory.StartNew(() =>
  359. {
  360. try
  361. {
  362. e.Set();
  363. while (true)
  364. {
  365. ct.ThrowIfCancellationRequested();
  366. }
  367. }
  368. finally
  369. {
  370. f.Set();
  371. }
  372. },
  373. CancellationToken.None) // Not forwarding ct because we are testing the case where the task is already running by the time cancellation is detected
  374. );
  375. e.WaitOne();
  376. var d = xs.Subscribe(_ => { });
  377. d.Dispose();
  378. f.WaitOne();
  379. while (!t.IsCompleted)
  380. {
  381. ;
  382. }
  383. ReactiveAssert.Throws<OperationCanceledException>(() => xs.Single());
  384. }
  385. }
  386. [TestMethod]
  387. public void Start_Action_UnsubscribeThenError_ErrorReportedAsUnobserved()
  388. {
  389. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  390. createTask => Observable.StartAsync(createTask),
  391. errorObservation =>
  392. {
  393. errorObservation.AssertExceptionReportedAsUnobserved();
  394. });
  395. }
  396. [TestMethod]
  397. public void Start_ActionWithCancel_UnsubscribeThenError_ErrorReportedAsUnobserved()
  398. {
  399. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  400. createTask => Observable.StartAsync(_ => createTask()),
  401. errorObservation =>
  402. {
  403. errorObservation.AssertExceptionReportedAsUnobserved();
  404. });
  405. }
  406. [TestMethod]
  407. public void Start_Action_WithScheduler_UnsubscribeThenError_ErrorReportedAsUnobserved()
  408. {
  409. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  410. createTask => Observable.StartAsync(createTask, TaskPoolScheduler.Default),
  411. errorObservation =>
  412. {
  413. errorObservation.AssertExceptionReportedAsUnobserved();
  414. });
  415. }
  416. [TestMethod]
  417. public void Start_ActionWithCancel_WithScheduler_UnsubscribeThenError_ErrorReportedAsUnobserved()
  418. {
  419. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  420. createTask => Observable.StartAsync(_ => createTask(), TaskPoolScheduler.Default),
  421. errorObservation =>
  422. {
  423. errorObservation.AssertExceptionReportedAsUnobserved();
  424. });
  425. }
  426. [TestMethod]
  427. public void Start_Action_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  428. {
  429. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  430. createTask => Observable.StartAsync(createTask, new TaskObservationOptions(null, ignoreExceptionsAfterUnsubscribe: true)),
  431. errorObservation =>
  432. {
  433. errorObservation.AssertExceptionNotReportedAsUnobserved();
  434. });
  435. }
  436. [TestMethod]
  437. public void Start_ActionWithCancel_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  438. {
  439. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  440. createTask => Observable.StartAsync(_ => createTask(), new TaskObservationOptions(null, ignoreExceptionsAfterUnsubscribe: true)),
  441. errorObservation =>
  442. {
  443. errorObservation.AssertExceptionNotReportedAsUnobserved();
  444. });
  445. }
  446. [TestMethod]
  447. public void Start_Action_WithScheduler_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  448. {
  449. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  450. createTask => Observable.StartAsync(createTask, new TaskObservationOptions(TaskPoolScheduler.Default, ignoreExceptionsAfterUnsubscribe: true)),
  451. errorObservation =>
  452. {
  453. errorObservation.AssertExceptionNotReportedAsUnobserved();
  454. });
  455. }
  456. [TestMethod]
  457. public void Start_ActionWithCancel_WithScheduler_IgnorePostUnsubscribeErrors_UnsubscribeThenError_ErrorNotReportedAsUnobserved()
  458. {
  459. Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  460. createTask => Observable.StartAsync(_ => createTask(), new TaskObservationOptions(TaskPoolScheduler.Default, ignoreExceptionsAfterUnsubscribe: true)),
  461. errorObservation =>
  462. {
  463. errorObservation.AssertExceptionNotReportedAsUnobserved();
  464. });
  465. }
  466. #if DESKTOPCLR
  467. [TestMethod]
  468. public void StartAsync_Action_Scheduler1()
  469. {
  470. var tcs = new TaskCompletionSource<int>();
  471. var e = new ManualResetEvent(false);
  472. var t = default(int);
  473. var xs = Observable.StartAsync(() => (Task)tcs.Task, Scheduler.Immediate);
  474. xs.Subscribe(res =>
  475. {
  476. t = Environment.CurrentManagedThreadId;
  477. e.Set();
  478. });
  479. tcs.SetResult(42);
  480. e.WaitOne();
  481. Assert.Equal(Environment.CurrentManagedThreadId, t);
  482. }
  483. [TestMethod]
  484. public void StartAsync_Action_Scheduler2()
  485. {
  486. var tcs = new TaskCompletionSource<int>();
  487. var e = new ManualResetEvent(false);
  488. var t = default(int);
  489. var xs = Observable.StartAsync(ct => (Task)tcs.Task, Scheduler.Immediate);
  490. xs.Subscribe(res =>
  491. {
  492. t = Environment.CurrentManagedThreadId;
  493. e.Set();
  494. });
  495. tcs.SetResult(42);
  496. e.WaitOne();
  497. Assert.Equal(Environment.CurrentManagedThreadId, t);
  498. }
  499. #endif
  500. #endregion
  501. private void Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  502. Func<Func<Task<int>>, IObservable<int>> createObservable,
  503. Action<TaskErrorObservation> testResults)
  504. {
  505. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core<int>(createObservable, testResults);
  506. }
  507. private void Start_Action_ErrorAfterUnsubscribeReportedAsUnobserved_Core(
  508. Func<Func<Task>, IObservable<Unit>> createObservable,
  509. Action<TaskErrorObservation> testResults)
  510. {
  511. Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core<Unit>(createObservable, testResults);
  512. }
  513. private void Start_Func_ErrorAfterUnsubscribeReportedAsUnobserved_Core<T>(
  514. Func<Func<Task<T>>, IObservable<T>> createObservable,
  515. Action<TaskErrorObservation> testResults)
  516. {
  517. using Barrier gate = new(2);
  518. using TaskErrorObservation errorObservation = new();
  519. var sub = errorObservation.SuscribeWithoutKeepingSourceReachable<T>(
  520. (setTask, exception) => createObservable(
  521. () => setTask(Task.Factory.StartNew<T>(
  522. () =>
  523. {
  524. // 1: Notify that task execution has begun
  525. gate.SignalAndWait();
  526. // 2: Wait until unsubscribe Dispose has returned
  527. gate.SignalAndWait();
  528. throw exception;
  529. })))
  530. .Subscribe());
  531. // 1: wait until task execution has begun
  532. gate.SignalAndWait();
  533. sub.Dispose();
  534. //sub = null;
  535. // 2: Notify that unsubscribe Dispose has returned
  536. gate.SignalAndWait();
  537. testResults(errorObservation);
  538. }
  539. }
  540. }