summaryrefslogtreecommitdiff
path: root/mcs/class/corlib/Test/System.Threading.Tasks/TaskFactoryTest.cs
blob: 857841e326ff72a4535ffcd095975c31b2c6857f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//
// TaskFactoryTest.cs
//
// Authors:
//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
//       Marek Safar <marek.safar@gmail.com>
// 
// Copyright (c) 2010 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

#if NET_4_0

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using NUnit.Framework;
#if !MOBILE
using NUnit.Framework.SyntaxHelpers;
#endif

namespace MonoTests.System.Threading.Tasks
{
	[TestFixture]
	public class TaskFactoryTests
	{
		class CompletedAsyncResult : IAsyncResult
		{
			public object AsyncState
			{
				get { throw new NotImplementedException (); }
			}

			public WaitHandle AsyncWaitHandle
			{
				get { throw new NotImplementedException (); }
			}

			public bool CompletedSynchronously
			{
				get { throw new NotImplementedException (); }
			}

			public bool IsCompleted
			{
				get { return true; }
			}
		}

		class TestAsyncResult : IAsyncResult
		{
			WaitHandle wh = new ManualResetEvent (true);

			public object AsyncState
			{
				get { throw new NotImplementedException (); }
			}

			public WaitHandle AsyncWaitHandle
			{
				get
				{
					return wh;
				}
			}

			public bool CompletedSynchronously
			{
				get { throw new NotImplementedException (); }
			}

			public bool IsCompleted
			{
				get { return false; }
			}
		}

		class TestScheduler : TaskScheduler
		{
			public bool ExecutedInline { get; set; }

			protected override void QueueTask (Task task)
			{
				throw new NotImplementedException ();
			}

			protected override bool TryDequeue (Task task)
			{
				throw new NotImplementedException ();
			}

			protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
			{
				if (taskWasPreviouslyQueued)
					throw new ArgumentException ("taskWasPreviouslyQueued");

				if (task.Status != TaskStatus.WaitingToRun)
					throw new ArgumentException ("task.Status");

				ExecutedInline = true;
				return TryExecuteTask (task);
			}

			protected override IEnumerable<Task> GetScheduledTasks ()
			{
				throw new NotImplementedException ();
			}
		}


		TaskFactory factory;

		[SetUp]
		public void Setup ()
		{
			this.factory = Task.Factory;
		}

		[Test]
		public void StartNewTest ()
		{
			bool result = false;
			factory.StartNew (() => result = true).Wait ();
			Assert.IsTrue (result);
		}

		[Test]
		public void NoDefaultScheduler ()
		{
			Assert.IsNull (factory.Scheduler, "#1");
		}

		[Test]
		public void ContinueWhenAll_Simple ()
		{
			var mre = new ManualResetEventSlim (false);

			Task[] tasks = new Task[3];
			tasks[0] = new Task (() => { Thread.Sleep (0); Assert.IsTrue (mre.Wait (3000)); });
			tasks[1] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
			tasks[2] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });

			bool ran = false;
			Task cont = factory.ContinueWhenAll (tasks, ts => {
				Assert.AreEqual (tasks, ts, "#0");
				ran = true;
			});

			foreach (Task t in tasks)
				t.Start ();

			mre.Set ();

			Assert.IsTrue (cont.Wait (1000), "#1");
			Assert.IsTrue (ran, "#2");
		}

		[Test]
		public void ContinueWhenAll_WithMixedCompletionState ()
		{
			var mre = new ManualResetEventSlim ();
			var task = Task.Factory.StartNew (() => mre.Wait (200));
			var contFailed = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnFaulted);
			var contCanceled = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnCanceled);
			var contSuccess = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnRanToCompletion);
			bool ran = false;

			var cont = Task.Factory.ContinueWhenAll (new Task[] { contFailed, contCanceled, contSuccess }, _ => ran = true);

			mre.Set ();
			cont.Wait (200);

			Assert.IsTrue (ran);
			Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status);
		}

		[Test]
		public void ContinueWhenAll_InvalidArguments ()
		{
			try {
				factory.ContinueWhenAll (null, delegate { });
				Assert.Fail ("#1");
			} catch (ArgumentNullException) {
			}

			try {
				factory.ContinueWhenAll (new Task[0], delegate { });
				Assert.Fail ("#2");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAll (new Task[] { null }, delegate { });
				Assert.Fail ("#3");
			} catch (ArgumentException) {
			}

			var tasks = new Task [] {
				factory.StartNew (delegate {})
			};

			try {
				factory.ContinueWhenAll (tasks, null);
				Assert.Fail ("#4");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAll (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
				Assert.Fail ("#5");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAll (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, null);
				Assert.Fail ("#6");
			} catch (ArgumentException) {
			}
		}

		[Test]
		public void ContinueWhenAll_WithExceptions ()
		{
			var t1 = Task.Factory.StartNew (() => { throw new ApplicationException ("Foo"); });
			var t2 = Task.Factory.StartNew (() => { throw new ApplicationException ("Bar"); });

			var cont = Task.Factory.ContinueWhenAll (new[] { t1, t2 }, delegate {});
			cont.Wait (200);

			Assert.IsTrue (t1.IsFaulted);
			Assert.IsTrue (t2.IsFaulted);
			Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status);
		}

		[Test]
		public void ContinueWhenAny_Simple ()
		{
			var t1 = new ManualResetEvent (false);
			var t2 = new ManualResetEvent (false);

			var tasks = new Task[2] {
				Task.Factory.StartNew (() => { t1.WaitOne (3000); }),
				Task.Factory.StartNew (() => { t2.WaitOne (3000); })
			};

			bool ran = false;
			var ct = new CancellationToken ();
			Task cont = factory.ContinueWhenAny (tasks, t => {
				Assert.AreEqual (tasks[0], t, "#1");
				ran = true;
			}, ct);

			Assert.AreEqual (TaskStatus.WaitingForActivation, cont.Status, "#2");

			t1.Set ();

			Assert.IsTrue (cont.Wait (2000), "#10");
			Assert.IsTrue (ran, "#11");

			t2.Set ();
		}

		[Test]
		public void ContinueWhenAny_WithResult ()
		{
			var tcs = new TaskCompletionSource<int>();
			tcs.SetResult(1);
			Task[] tasks = new[] { tcs.Task };
			var res = Task.Factory.ContinueWhenAny (tasks, l => 4);
			Assert.AreEqual (4, res.Result);
		}

		[Test]
		public void ContinueWhenAny_InvalidArguments ()
		{
			try {
				factory.ContinueWhenAny (null, delegate { });
				Assert.Fail ("#1");
			} catch (ArgumentNullException) {
			}

			try {
				factory.ContinueWhenAny (new Task[0], delegate { });
				Assert.Fail ("#2");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAny (new Task[] { null }, delegate { });
				Assert.Fail ("#3");
			} catch (ArgumentException) {
			}

			var tasks = new Task [] {
				factory.StartNew (delegate {})
			};

			try {
				factory.ContinueWhenAny (tasks, null);
				Assert.Fail ("#4");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
				Assert.Fail ("#5");
			} catch (ArgumentException) {
			}

			try {
				factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, null);
				Assert.Fail ("#6");
			} catch (ArgumentException) {
			}
		}

		[Test]
		public void FromAsyncBeginInvoke_WithResult ()
		{
			bool result = false;

			Func<int, int> func = (i) => {
				Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
				result = true; return i + 3;
			};

			var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
			Assert.IsTrue (task.Wait (5000), "#1");
			Assert.IsTrue (result, "#2");
			Assert.AreEqual (4, task.Result, "#3");
			Assert.AreEqual ("state", (string) task.AsyncState, "#4");
			Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
		}

		[Test]
		public void FromAsyncBeginMethod_DirectResult ()
		{
			bool result = false;
			bool continuationTest = false;

			Func<int, int> func = (i) => { result = true; return i + 3; };
			Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
			var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
			task.Wait ();
			cont.Wait ();

			Assert.IsTrue (result);
			Assert.IsTrue (continuationTest);
			Assert.AreEqual (4, task.Result);
		}

		[Test]
		public void FromAsyncBeginMethod_Exception ()
		{
			bool result = false;
			bool continuationTest = false;

			Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); };
			Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
			var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
			try {
				task.Wait (2000);
			} catch { }
			Assert.IsTrue (cont.Wait (2000), "#1");

			Assert.IsTrue (result);
			Assert.IsTrue (continuationTest);
			Assert.IsNotNull (task.Exception);
			var agg = task.Exception;
			Assert.AreEqual (1, agg.InnerExceptions.Count);
			Assert.That (agg.InnerExceptions[0], Is.TypeOf (typeof (ApplicationException)));
			Assert.AreEqual (TaskStatus.Faulted, task.Status);

			try {
				var a = task.Result;
				Assert.Fail ();
			} catch (AggregateException) {
			}
		}

		[Test]
		public void FromAsync_ArgumentsCheck ()
		{
			var result = new CompletedAsyncResult ();
			try {
				factory.FromAsync (null, l => { });
				Assert.Fail ("#1");
			} catch (ArgumentNullException) {
			}

			try {
				factory.FromAsync (result, null);
				Assert.Fail ("#2");
			} catch (ArgumentNullException) {
			}

			try {
				factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
				Assert.Fail ("#3");
			} catch (ArgumentOutOfRangeException) {
			}

			try {
				factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
				Assert.Fail ("#4");
			} catch (ArgumentOutOfRangeException) {
			}

			try {
				factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
				Assert.Fail ("#5");
			} catch (ArgumentNullException) {
			}

			try {
				factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
				Assert.Fail ("#6");
			} catch (ArgumentNullException) {
			}

			try {
				factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
				Assert.Fail ("#7");
			} catch (ArgumentOutOfRangeException) {
			}
		}

		[Test]
		public void FromAsync_Completed ()
		{
			var completed = new CompletedAsyncResult ();
			bool? valid = null;

			Action<IAsyncResult> end = l => {
				Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
				valid = l == completed;
			};
			Task task = factory.FromAsync (completed, end);
			Assert.IsTrue (valid == true, "#1");
		}

		[Test]
		public void FromAsync_CompletedWithException ()
		{
			var completed = new CompletedAsyncResult ();

			Action<IAsyncResult> end = l => {
				throw new ApplicationException ();
			};
			Task task = factory.FromAsync (completed, end);
			Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
		}

		[Test]
		public void FromAsync_CompletedCanceled ()
		{
			var completed = new CompletedAsyncResult ();

			Action<IAsyncResult> end = l => {
				throw new OperationCanceledException ();
			};
			Task task = factory.FromAsync (completed, end);
			Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
			Assert.IsNull (task.Exception, "#2");
		}

		[Test]
		public void FromAsync_SimpleAsyncResult ()
		{
			var result = new TestAsyncResult ();
			bool called = false;

			var task = factory.FromAsync (result, l => {
				called = true;
			});

			Assert.IsTrue (task.Wait (1000), "#1");
			Assert.IsTrue (called, "#2");
		}

		[Test]
		public void FromAsync_ResultException ()
		{
			var result = new TestAsyncResult ();

			var task = factory.FromAsync (result, l => {
				throw new ApplicationException ();
			});

			try {
				Assert.IsFalse (task.Wait (1000), "#1");
			} catch (AggregateException) {
			}

			Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
		}

		[Test]
		public void FromAsync_ReturnInt ()
		{
			var result = new TestAsyncResult ();
			bool called = false;

			var task = factory.FromAsync<int> (result, l => {
				called = true;
				return 4;
			});

			Assert.IsTrue (task.Wait (1000), "#1");
			Assert.IsTrue (called, "#2");
			Assert.AreEqual (4, task.Result, "#3");
		}

		[Test]
		public void FromAsync_Scheduler_Explicit ()
		{
			var result = new TestAsyncResult ();
			bool called = false;
			var scheduler = new TestScheduler ();

			var task = factory.FromAsync (result, l => {
				called = true;
			}, TaskCreationOptions.None, scheduler);

			Assert.IsTrue (task.Wait (5000), "#1");
			Assert.IsTrue (called, "#2");
			Assert.IsTrue (scheduler.ExecutedInline, "#3");
		}

		[Test]
		public void FromAsync_Scheduler_Implicit ()
		{
			var result = new TestAsyncResult ();
			bool called = false;
			var scheduler = new TestScheduler ();

			factory = new TaskFactory (scheduler);

			Task task = factory.FromAsync (result, l => {
				Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
				called = true;
			}, TaskCreationOptions.AttachedToParent);

			Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
			Assert.IsNull (task.AsyncState, "#2");
			Assert.IsTrue (task.Wait (5000), "#3");
			Assert.IsTrue (called, "#4");
			Assert.IsTrue (scheduler.ExecutedInline, "#5");
		}

		[Test]
		public void FromAsync_BeginCallback ()
		{
			bool called = false;
			bool called2 = false;

			var task = factory.FromAsync (
				(a, b, c) => {
					if (a != "h")
						Assert.Fail ("#10");

					if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
						Assert.Fail ("#11");

					Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");

					called2 = true;
					b.Invoke (null);
					return null;
				},
				l => {
					called = true;
				},
				"h", TaskCreationOptions.AttachedToParent);

			Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
			Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
			Assert.IsTrue (task.Wait (5000), "#3");
			Assert.IsTrue (called, "#4");
			Assert.IsTrue (called2, "#5");
		}

		[Test]
		public void StartNewCancelled ()
		{
			var ct = new CancellationToken (true);

			var task = factory.StartNew (() => Assert.Fail ("Should never be called"), ct);
			try {
				task.Start ();
				Assert.Fail ("#1");
			} catch (InvalidOperationException) {
			}

			Assert.IsTrue (task.IsCanceled, "#2");

			task = factory.StartNew (() => { }, ct);
			try {
				task.Wait ();
			} catch (AggregateException e) {
				Assert.IsTrue (task.IsCanceled, "#3");
				Assert.That (e.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#4");
			}
		}
	}
}
#endif