Add [Category ("NotWorking")] to failing test.
[mono.git] / mcs / class / corlib / Test / System.Threading.Tasks / TaskSchedulerTest.cs
1 // TaskSchedulerTest.cs
2 //
3 // Copyright (c) 2008 Jérémie "Garuma" Laval
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
22 //
23 //
24
25 #if NET_4_0
26
27 using System;
28 using System.Threading;
29 using System.Threading.Tasks;
30 using System.Collections.Generic;
31
32 using NUnit.Framework;
33 #if !MOBILE
34 using NUnit.Framework.SyntaxHelpers;
35 #endif
36
37 namespace MonoTests.System.Threading.Tasks
38 {
39         [TestFixture]
40         public class TaskSchedulerTests
41         {
42                 class LazyCatScheduler : TaskScheduler
43                 {
44                         public TaskStatus ExecuteInlineStatus
45                         {
46                                 get;
47                                 set;
48                         }
49
50                         protected override void QueueTask (Task task)
51                         {
52                                 throw new NotImplementedException ();
53                         }
54
55                         protected override bool TryDequeue (Task task)
56                         {
57                                 throw new NotImplementedException ();
58                         }
59
60                         protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
61                         {
62                                 ExecuteInlineStatus = task.Status;
63                                 return true;
64                         }
65
66                         protected override IEnumerable<Task> GetScheduledTasks ()
67                         {
68                                 throw new NotImplementedException ();
69                         }
70                 }
71
72                 class DefaultScheduler : TaskScheduler
73                 {
74                         protected override IEnumerable<Task> GetScheduledTasks ()
75                         {
76                                 throw new NotImplementedException ();
77                         }
78
79                         protected override void QueueTask (Task task)
80                         {
81                                 throw new NotImplementedException ();
82                         }
83
84                         protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
85                         {
86                                 throw new NotImplementedException ();
87                         }
88
89                         public void TestDefaultMethod ()
90                         {
91                                 Assert.IsFalse (TryDequeue (null), "#1");
92                         }
93                 }
94
95                 [Test]
96                 public void FromCurrentSynchronizationContextTest_Invalid()
97                 {
98                         var c = SynchronizationContext.Current;
99                         try {
100                                 SynchronizationContext.SetSynchronizationContext (null);
101                                 TaskScheduler.FromCurrentSynchronizationContext ();
102                                 Assert.Fail ("#1");
103                         } catch (InvalidOperationException) {
104                         } finally {
105                                 SynchronizationContext.SetSynchronizationContext (c);
106                         }
107                 }
108
109                 [Test]
110                 public void BasicRunSynchronouslyTest ()
111                 {
112                         bool ran = false;
113                         var t = new Task (() => ran = true);
114
115                         t.RunSynchronously ();
116                         Assert.IsTrue (t.IsCompleted);
117                         Assert.IsFalse (t.IsFaulted);
118                         Assert.IsFalse (t.IsCanceled);
119                         Assert.IsTrue (ran);
120                 }
121
122                 [Test]
123                 public void RunSynchronouslyButNoExecutionTest ()
124                 {
125                         TaskSchedulerException ex = null;
126
127                         var ts = new LazyCatScheduler ();
128                         Task t = new Task (() => {});
129
130                         try {
131                                 t.RunSynchronously (ts);
132                         } catch (TaskSchedulerException e) {
133                                 ex = e;
134                         }
135
136                         Assert.IsNotNull (ex);
137                         Assert.IsNotNull (ex.InnerException);
138                         Assert.That (ex.InnerException, Is.TypeOf (typeof (InvalidOperationException)));
139                 }
140
141                 [Test]
142                 public void RunSynchronouslyTaskStatusTest ()
143                 {
144                         var ts = new LazyCatScheduler ();
145                         var t = new Task (() => { });
146
147                         try {
148                                 t.RunSynchronously (ts);
149                         } catch {}
150                         Assert.AreEqual (TaskStatus.WaitingToRun, ts.ExecuteInlineStatus);
151                 }
152
153                 static int finalizerThreadId = -1;
154         
155                 class FinalizerCatcher
156                 {
157                         ~FinalizerCatcher ()
158                         {
159                                 finalizerThreadId = Thread.CurrentThread.ManagedThreadId;
160                         }
161                 }
162
163                 [Test]
164                 public void DefaultBehaviourTest ()
165                 {
166                         var s = new DefaultScheduler ();
167                         s.TestDefaultMethod ();
168                 }
169
170                 // This test doesn't work if the GC uses multiple finalizer thread.
171                 // For now it's fine since only one thread is used
172                 [Test]
173                 // Depends on objects getting GCd plus installs an EH handler which catches
174                 // exceptions thrown by other tasks
175                 [Category ("NotWorking")]
176                 public void UnobservedTaskExceptionOnFinalizerThreadTest ()
177                 {
178                         var foo = new FinalizerCatcher ();
179                         foo = null;
180                         GC.Collect ();
181                         GC.WaitForPendingFinalizers ();
182                         // Same than following test, if GC didn't run don't execute the rest of this test
183                         if (finalizerThreadId == -1)
184                                 return;
185
186                         int evtThreadId = -2;
187                         TaskScheduler.UnobservedTaskException += delegate {
188                                 evtThreadId = Thread.CurrentThread.ManagedThreadId;
189                         };
190                         var evt = new ManualResetEventSlim ();
191                         CreateAndForgetFaultedTask (evt);
192                         evt.Wait (500);
193                         Thread.Sleep (100);
194                         GC.Collect ();
195                         GC.WaitForPendingFinalizers ();
196                         Assert.AreEqual (finalizerThreadId, evtThreadId, "Should be ran on finalizer thread");
197                 }
198
199                 [Test]
200                 // Depends on objects getting GCd plus installs an EH handler which catches
201                 // exceptions thrown by other tasks
202                 [Category ("NotWorking")]
203                 public void UnobservedTaskExceptionArgumentTest ()
204                 {
205                         bool ran = false;
206                         bool senderIsRight = false;
207                         UnobservedTaskExceptionEventArgs args = null;
208
209                         TaskScheduler.UnobservedTaskException += (o, a) => {
210                                 senderIsRight = o.GetType ().ToString () == "System.Threading.Tasks.Task";
211                                 args = a;
212                                 ran = true;
213                         };
214
215                         var evt = new ManualResetEventSlim ();
216                         CreateAndForgetFaultedTask (evt);
217                         evt.Wait (500);
218                         Thread.Sleep (100);
219                         GC.Collect ();
220                         GC.WaitForPendingFinalizers ();
221
222                         // GC is too unreliable for some reason in that test, so backoff if finalizer wasn't ran
223                         // it needs to be run for the above test to work though (♥)
224                         if (!ran)
225                                 return;
226
227                         Assert.IsNotNull (args.Exception);
228                         Assert.IsNotNull (args.Exception.InnerException);
229                         Assert.AreEqual ("foo", args.Exception.InnerException.Message);
230                         Assert.IsFalse (args.Observed);
231                         Assert.IsTrue (senderIsRight, "Sender is a task");
232                 }
233
234                 // We use this intermediary method to improve chances of GC kicking
235                 static void CreateAndForgetFaultedTask (ManualResetEventSlim evt)
236                 {
237                         Task.Factory.StartNew (() => { evt.Set (); throw new Exception ("foo"); });
238                 }
239         }
240 }
241 #endif