[corlib] Disable a test that is incompatible with how nunitlite runs tests
[mono.git] / mcs / class / corlib / Test / System.Runtime.CompilerServices / TaskAwaiterTest.cs
1 //
2 // TaskAwaiterTest.cs
3 //
4 // Authors:
5 //      Marek Safar  <marek.safar@gmail.com>
6 //
7 // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 //
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 //
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29
30 using System;
31 using System.Threading;
32 using System.Threading.Tasks;
33 using NUnit.Framework;
34 using System.Runtime.CompilerServices;
35 using System.Collections.Generic;
36 using System.Collections;
37 using System.Collections.Concurrent;
38
39 namespace MonoTests.System.Runtime.CompilerServices
40 {
41         [TestFixture]
42         public class TaskAwaiterTest
43         {
44                 class Scheduler : TaskScheduler
45                 {
46                         string name;
47                         int ic, qc;
48
49                         public Scheduler (string name)
50                         {
51                                 this.name = name;
52                         }
53
54                         public int InlineCalls { get { return ic; } }
55                         public int QueueCalls { get { return qc; } }
56
57                         protected override IEnumerable<Task> GetScheduledTasks ()
58                         {
59                                 throw new NotImplementedException ();
60                         }
61
62                         protected override void QueueTask (Task task)
63                         {
64                                 Interlocked.Increment (ref qc);
65                                 ThreadPool.QueueUserWorkItem (o => {
66                                         TryExecuteTask (task);
67                                 });
68                         }
69
70                         protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
71                         {
72                                 Interlocked.Increment (ref ic);
73                                 return false;
74                         }
75
76                         public override string ToString ()
77                         {
78                                 return "Scheduler-" + name;
79                         }
80                 }
81
82                 class SingleThreadSynchronizationContext : SynchronizationContext
83                 {
84                         readonly Queue _queue = new Queue ();
85
86                         public void RunOnCurrentThread ()
87                         {
88                                 while (_queue.Count != 0) {
89                                         var workItem = (KeyValuePair<SendOrPostCallback, object>) _queue.Dequeue ();
90                                         workItem.Key (workItem.Value);
91                                 }
92                         }
93                                 
94                         public override void Post (SendOrPostCallback d, object state)
95                         {
96                                 if (d == null) {
97                                         throw new ArgumentNullException ("d");
98                                 }
99
100                                 _queue.Enqueue (new KeyValuePair<SendOrPostCallback, object> (d, state));
101                         }
102
103                         public override void Send (SendOrPostCallback d, object state)
104                         {
105                                 throw new NotSupportedException ("Synchronously sending is not supported.");
106                         }
107                 }
108
109                 class NestedSynchronizationContext : SynchronizationContext
110                 {
111                         Thread thread;
112                         readonly ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> workQueue = new ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> ();
113                         readonly AutoResetEvent workReady = new AutoResetEvent (false);
114
115                         public NestedSynchronizationContext ()
116                         {
117                                 thread = new Thread (WorkerThreadProc) { IsBackground = true };
118                                 thread.Start ();
119                         }
120
121                         public override void Post (SendOrPostCallback d, object state)
122                         {
123                                 var context = ExecutionContext.Capture ();
124                                 workQueue.Enqueue (Tuple.Create (d, state, context));
125                                 workReady.Set ();
126                         }
127
128                         void WorkerThreadProc ()
129                         {
130                                 if (!workReady.WaitOne (10000))
131                                         return;
132
133                                 Tuple<SendOrPostCallback, object, ExecutionContext> work;
134
135                                 while (workQueue.TryDequeue (out work)) {
136                                         ExecutionContext.Run (work.Item3, _ => {
137                                                 var oldSyncContext = SynchronizationContext.Current;
138                                                 SynchronizationContext.SetSynchronizationContext (this);
139                                                 work.Item1 (_);
140                                                 SynchronizationContext.SetSynchronizationContext (oldSyncContext);
141                                         }, work.Item2); 
142                                 }
143                         }
144                 }
145
146                 string progress;
147                 SynchronizationContext sc;
148                 ManualResetEvent mre;
149
150                 [SetUp]
151                 public void Setup ()
152                 {
153                         sc = SynchronizationContext.Current;
154                 }
155
156                 [TearDown]
157                 public void TearDown ()
158                 {
159                         SynchronizationContext.SetSynchronizationContext (sc);
160                 }
161
162                 [Test]
163                 public void GetResultFaulted ()
164                 {
165                         TaskAwaiter awaiter;
166
167                         var task = new Task (() => { throw new ApplicationException (); });
168                         awaiter = task.GetAwaiter ();
169                         task.RunSynchronously (TaskScheduler.Current);
170
171
172                         Assert.IsTrue (awaiter.IsCompleted);
173
174                         try {
175                                 awaiter.GetResult ();
176                                 Assert.Fail ();
177                         } catch (ApplicationException) {
178                         }
179                 }
180
181                 [Test]
182                 public void GetResultCanceled ()
183                 {
184                         TaskAwaiter awaiter;
185
186                         var token = new CancellationToken (true);
187                         var task = new Task (() => { }, token);
188                         awaiter = task.GetAwaiter ();
189
190                         try {
191                                 awaiter.GetResult ();
192                                 Assert.Fail ();
193                         } catch (TaskCanceledException) {
194                         }
195                 }
196
197                 [Test]
198                 public void GetResultWaitOnCompletion ()
199                 {
200                         TaskAwaiter awaiter;
201                                 
202                         var task = Task.Delay (30);
203                         awaiter = task.GetAwaiter ();
204                                 
205                         awaiter.GetResult ();
206                         Assert.AreEqual (TaskStatus.RanToCompletion, task.Status);
207                 }
208
209                 [Test]
210                 public void CustomScheduler ()
211                 {
212                         // some test runners (e.g. Touch.Unit) will execute this on the main thread and that would lock them
213                         if (!Thread.CurrentThread.IsBackground)
214                                 Assert.Ignore ("Current thread is not running in the background.");
215
216                         var a = new Scheduler ("a");
217                         var b = new Scheduler ("b");
218
219                         var t = TestCS (a, b);
220                         Assert.IsTrue (t.Wait (3000), "#0");
221                         Assert.AreEqual (0, t.Result, "#1");
222                         Assert.AreEqual (0, b.InlineCalls, "#2b");
223                         Assert.IsTrue (a.QueueCalls == 1 || a.QueueCalls == 2, "#3a");
224                         Assert.AreEqual (1, b.QueueCalls, "#3b");
225                 }
226
227                 static async Task<int> TestCS (TaskScheduler schedulerA, TaskScheduler schedulerB)
228                 {
229                         var res = await Task.Factory.StartNew (async () => {
230                                 if (TaskScheduler.Current != schedulerA)
231                                         return 1;
232
233                                 await Task.Factory.StartNew (
234                                         () => {
235                                                 if (TaskScheduler.Current != schedulerB)
236                                                         return 2;
237
238                                                 return 0;
239                                         }, CancellationToken.None, TaskCreationOptions.None, schedulerB);
240
241                                 if (TaskScheduler.Current != schedulerA)
242                                         return 3;
243
244                                 return 0;
245                         }, CancellationToken.None, TaskCreationOptions.None, schedulerA);
246
247                         return res.Result;
248                 }
249
250                 [Test]
251                 [Ignore ("Incompatible with nunitlite")]
252                 public void FinishedTaskOnCompleted ()
253                 {
254                         var mres = new ManualResetEvent (false);
255                         var mres2 = new ManualResetEvent (false);
256
257                         var tcs = new TaskCompletionSource<object> ();
258                         tcs.SetResult (null);
259                         var task = tcs.Task;
260
261                         var awaiter = task.GetAwaiter ();
262                         Assert.IsTrue (awaiter.IsCompleted, "#1");
263
264                         awaiter.OnCompleted(() => { 
265                                 if (mres.WaitOne (1000))
266                                         mres2.Set ();
267                         });
268
269                         mres.Set ();
270                         // this will only terminate correctly if the test was not executed from the main thread
271                         // e.g. nunitlite/Touch.Unit defaults to run tests on the main thread and this will return false
272                         Assert.AreEqual (Thread.CurrentThread.IsBackground, mres2.WaitOne (2000), "#2");;
273                 }
274
275                 [Test]
276                 public void CompletionOnSameCustomSynchronizationContext ()
277                 {
278                         progress = "";
279                         var syncContext = new SingleThreadSynchronizationContext ();
280                         SynchronizationContext.SetSynchronizationContext (syncContext);
281
282                         syncContext.Post (delegate {
283                                 Go (syncContext);
284                         }, null);
285
286                         // Custom message loop
287                         var cts = new CancellationTokenSource ();
288                         cts.CancelAfter (5000);
289                         while (progress.Length != 3 && !cts.IsCancellationRequested) {
290                                 syncContext.RunOnCurrentThread ();
291                                 Thread.Sleep (0);
292                         }
293
294                         Assert.AreEqual ("123", progress);
295                 }
296
297                 async void Go (SynchronizationContext ctx)
298                 {
299                         await Wait (ctx);
300
301                         progress += "2";
302                 }
303
304                 async Task Wait (SynchronizationContext ctx)
305                 {
306                         await Task.Delay (10); // Force block suspend/return
307
308                         ctx.Post (l => progress += "3", null);
309
310                         progress += "1";
311
312                         // Exiting same context - no need to post continuation
313                 }
314
315                 [Test]
316                 public void CompletionOnDifferentCustomSynchronizationContext ()
317                 {
318                         mre = new ManualResetEvent (false);
319                         progress = "";
320                         var syncContext = new SingleThreadSynchronizationContext ();
321                         SynchronizationContext.SetSynchronizationContext (syncContext);
322
323                         syncContext.Post (delegate {
324                                 Task t = new Task (delegate() { });
325                                 Go2 (syncContext, t);
326                                 t.Start ();
327                         }, null);
328
329                         // Custom message loop
330                         var cts = new CancellationTokenSource ();
331                         cts.CancelAfter (5000);
332                         while (progress.Length != 3 && !cts.IsCancellationRequested) {
333                                 syncContext.RunOnCurrentThread ();
334                                 Thread.Sleep (0);
335                         }
336
337                         Assert.AreEqual ("13xa2", progress);
338                 }
339
340                 async void Go2 (SynchronizationContext ctx, Task t)
341                 {
342                         await Wait2 (ctx, t);
343
344                         progress += "a";
345
346                         if (mre.WaitOne (5000))
347                                 progress += "2";
348                         else
349                                 progress += "b";
350                 }
351
352                 async Task Wait2 (SynchronizationContext ctx, Task t)
353                 {
354                         await t; // Force block suspend/return
355
356                         ctx.Post (l => {
357                                 progress += "3";
358                                 mre.Set ();
359                                 progress += "x";
360                         }, null);
361
362                         progress += "1";
363
364                         SynchronizationContext.SetSynchronizationContext (null);
365                 }
366
367                 [Test]
368                 public void NestedLeakingSynchronizationContext ()
369                 {
370                         var sc = SynchronizationContext.Current;
371                         if (sc == null)
372                                 Assert.IsTrue (NestedLeakingSynchronizationContext_MainAsync (sc).Wait (5000), "#1");
373                         else
374                                 Assert.Ignore ("NestedSynchronizationContext may never complete on custom context");
375                 }
376
377                 static async Task NestedLeakingSynchronizationContext_MainAsync (SynchronizationContext sc)
378                 {
379                         Assert.AreSame (sc, SynchronizationContext.Current, "#1");
380                         await NestedLeakingSynchronizationContext_DoWorkAsync ();
381                         Assert.AreSame (sc, SynchronizationContext.Current, "#2");
382                 }
383
384                 static async Task NestedLeakingSynchronizationContext_DoWorkAsync ()
385                 {
386                         var sc = new NestedSynchronizationContext ();
387                         SynchronizationContext.SetSynchronizationContext (sc);
388
389                         Assert.AreSame (sc, SynchronizationContext.Current);
390                         await Task.Yield ();
391                         Assert.AreSame (sc, SynchronizationContext.Current);
392                 }
393         }
394 }
395