77
|
1 using System;
|
|
2 using System.Reflection;
|
|
3 using System.Threading;
|
|
4 using Implab.Parallels;
|
|
5
|
|
6 #if MONO
|
|
7
|
|
8 using NUnit.Framework;
|
|
9 using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
|
|
10 using TestMethod = NUnit.Framework.TestAttribute;
|
|
11
|
|
12 #else
|
|
13
|
|
14 using Microsoft.VisualStudio.TestTools.UnitTesting;
|
|
15
|
|
16 #endif
|
|
17
|
|
18 namespace Implab.Test {
|
|
19 [TestClass]
|
|
20 public class AsyncTests {
|
|
21 [TestMethod]
|
|
22 public void ResolveTest() {
|
|
23 int res = -1;
|
|
24 var p = new Promise<int>();
|
|
25 p.Then(x => res = x);
|
|
26 p.Resolve(100);
|
|
27
|
|
28 Assert.AreEqual(100, res);
|
|
29 }
|
|
30
|
|
31 [TestMethod]
|
|
32 public void RejectTest() {
|
|
33 int res = -1;
|
|
34 Exception err = null;
|
|
35
|
|
36 var p = new Promise<int>();
|
|
37 p.Then(
|
|
38 x => res = x,
|
|
39 e => {
|
|
40 err = e;
|
|
41 return -2;
|
|
42 }
|
|
43 );
|
|
44 p.Reject(new ApplicationException("error"));
|
|
45
|
|
46 Assert.AreEqual(res, -1);
|
|
47 Assert.AreEqual(err.Message, "error");
|
|
48
|
|
49 }
|
|
50
|
|
51 [TestMethod]
|
|
52 public void CancelExceptionTest() {
|
|
53 var p = new Promise<bool>();
|
|
54 p.Cancel();
|
|
55
|
|
56 var p2 = p.Cancelled(() => {
|
|
57 throw new ApplicationException("CANCELLED");
|
|
58 });
|
|
59
|
|
60 try {
|
|
61 p2.Join();
|
|
62 Assert.Fail();
|
|
63 } catch (ApplicationException err) {
|
|
64 Assert.AreEqual("CANCELLED", err.InnerException.Message);
|
|
65 }
|
|
66
|
|
67 }
|
|
68
|
|
69 [TestMethod]
|
|
70 public void ContinueOnCancelTest() {
|
|
71 var p = new Promise<bool>();
|
|
72 p.Cancel();
|
|
73
|
|
74 var p2 = p
|
|
75 .Cancelled(() => {
|
|
76 throw new ApplicationException("CANCELLED");
|
|
77 })
|
|
78 .Error(e => true);
|
|
79
|
|
80 Assert.AreEqual(true, p2.Join());
|
|
81 }
|
|
82
|
|
83 [TestMethod]
|
|
84 public void JoinSuccessTest() {
|
|
85 var p = new Promise<int>();
|
|
86 p.Resolve(100);
|
|
87 Assert.AreEqual(p.Join(), 100);
|
|
88 }
|
|
89
|
|
90 [TestMethod]
|
|
91 public void JoinFailTest() {
|
|
92 var p = new Promise<int>();
|
|
93 p.Reject(new ApplicationException("failed"));
|
|
94
|
|
95 try {
|
|
96 p.Join();
|
|
97 throw new ApplicationException("WRONG!");
|
|
98 } catch (TargetInvocationException err) {
|
|
99 Assert.AreEqual(err.InnerException.Message, "failed");
|
|
100 } catch {
|
|
101 Assert.Fail("Got wrong excaption");
|
|
102 }
|
|
103 }
|
|
104
|
|
105 [TestMethod]
|
|
106 public void MapTest() {
|
|
107 var p = new Promise<int>();
|
|
108
|
|
109 var p2 = p.Then(x => x.ToString());
|
|
110 p.Resolve(100);
|
|
111
|
|
112 Assert.AreEqual(p2.Join(), "100");
|
|
113 }
|
|
114
|
|
115 [TestMethod]
|
|
116 public void FixErrorTest() {
|
|
117 var p = new Promise<int>();
|
|
118
|
|
119 var p2 = p.Error(e => 101);
|
|
120
|
|
121 p.Reject(new Exception());
|
|
122
|
|
123 Assert.AreEqual(p2.Join(), 101);
|
|
124 }
|
|
125
|
|
126 [TestMethod]
|
|
127 public void ChainTest() {
|
|
128 var p1 = new Promise<int>();
|
|
129
|
|
130 var p3 = p1.Chain(x => {
|
|
131 var p2 = new Promise<string>();
|
|
132 p2.Resolve(x.ToString());
|
|
133 return p2;
|
|
134 });
|
|
135
|
|
136 p1.Resolve(100);
|
|
137
|
|
138 Assert.AreEqual(p3.Join(), "100");
|
|
139 }
|
|
140
|
|
141 [TestMethod]
|
105
|
142 public void ChainFailTest() {
|
|
143 var p1 = new Promise<int>();
|
|
144
|
|
145 var p3 = p1.Chain(x => {
|
|
146 var p2 = new Promise<string>();
|
|
147 p2.Reject(new Exception("DIE!!!"));
|
|
148 return p2;
|
|
149 });
|
|
150
|
|
151 p1.Resolve(100);
|
|
152
|
|
153 Assert.IsTrue(p3.IsResolved);
|
|
154 }
|
|
155
|
|
156 [TestMethod]
|
77
|
157 public void PoolTest() {
|
|
158 var pid = Thread.CurrentThread.ManagedThreadId;
|
|
159 var p = AsyncPool.Invoke(() => Thread.CurrentThread.ManagedThreadId);
|
|
160
|
|
161 Assert.AreNotEqual(pid, p.Join());
|
|
162 }
|
|
163
|
|
164 [TestMethod]
|
|
165 public void WorkerPoolSizeTest() {
|
81
|
166 var pool = new WorkerPool(5, 10, 1);
|
77
|
167
|
|
168 Assert.AreEqual(5, pool.PoolSize);
|
|
169
|
|
170 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
171 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
172 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
173
|
|
174 Assert.AreEqual(5, pool.PoolSize);
|
|
175
|
|
176 for (int i = 0; i < 100; i++)
|
|
177 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
178 Thread.Sleep(200);
|
|
179 Assert.AreEqual(10, pool.PoolSize);
|
|
180
|
|
181 pool.Dispose();
|
|
182 }
|
|
183
|
|
184 [TestMethod]
|
|
185 public void WorkerPoolCorrectTest() {
|
|
186 var pool = new WorkerPool(0,1000,100);
|
|
187
|
|
188 const int iterations = 1000;
|
|
189 int pending = iterations;
|
|
190 var stop = new ManualResetEvent(false);
|
|
191
|
|
192 var count = 0;
|
|
193 for (int i = 0; i < iterations; i++) {
|
|
194 pool
|
|
195 .Invoke(() => 1)
|
|
196 .Then(x => Interlocked.Add(ref count, x))
|
|
197 .Then(x => Math.Log10(x))
|
|
198 .Anyway(() => {
|
|
199 Interlocked.Decrement(ref pending);
|
|
200 if (pending == 0)
|
|
201 stop.Set();
|
|
202 });
|
|
203 }
|
|
204
|
|
205 stop.WaitOne();
|
|
206
|
|
207 Assert.AreEqual(iterations, count);
|
|
208 Console.WriteLine("Max threads: {0}", pool.MaxRunningThreads);
|
|
209 pool.Dispose();
|
|
210
|
|
211 }
|
|
212
|
|
213 [TestMethod]
|
|
214 public void WorkerPoolDisposeTest() {
|
|
215 var pool = new WorkerPool(5, 20);
|
|
216 Assert.AreEqual(5, pool.PoolSize);
|
|
217 pool.Dispose();
|
|
218 Thread.Sleep(500);
|
|
219 Assert.AreEqual(0, pool.PoolSize);
|
|
220 pool.Dispose();
|
|
221 }
|
|
222
|
|
223 [TestMethod]
|
|
224 public void MTQueueTest() {
|
|
225 var queue = new MTQueue<int>();
|
|
226 int res;
|
|
227
|
|
228 queue.Enqueue(10);
|
|
229 Assert.IsTrue(queue.TryDequeue(out res));
|
|
230 Assert.AreEqual(10, res);
|
|
231 Assert.IsFalse(queue.TryDequeue(out res));
|
|
232
|
|
233 for (int i = 0; i < 1000; i++)
|
|
234 queue.Enqueue(i);
|
|
235
|
|
236 for (int i = 0; i < 1000; i++) {
|
|
237 queue.TryDequeue(out res);
|
|
238 Assert.AreEqual(i, res);
|
|
239 }
|
|
240
|
|
241 int writers = 0;
|
|
242 int readers = 0;
|
|
243 var stop = new ManualResetEvent(false);
|
|
244 int total = 0;
|
|
245
|
|
246 const int itemsPerWriter = 10000;
|
|
247 const int writersCount = 10;
|
|
248
|
|
249 for (int i = 0; i < writersCount; i++) {
|
|
250 Interlocked.Increment(ref writers);
|
|
251 AsyncPool
|
|
252 .InvokeNewThread(() => {
|
|
253 for (int ii = 0; ii < itemsPerWriter; ii++) {
|
|
254 queue.Enqueue(1);
|
|
255 }
|
|
256 return 1;
|
|
257 })
|
|
258 .Anyway(() => Interlocked.Decrement(ref writers));
|
|
259 }
|
|
260
|
|
261 for (int i = 0; i < 10; i++) {
|
|
262 Interlocked.Increment(ref readers);
|
|
263 AsyncPool
|
|
264 .InvokeNewThread(() => {
|
|
265 int t;
|
|
266 do {
|
|
267 while (queue.TryDequeue(out t))
|
|
268 Interlocked.Add(ref total, t);
|
|
269 } while (writers > 0);
|
|
270 return 1;
|
|
271 })
|
|
272 .Anyway(() => {
|
|
273 Interlocked.Decrement(ref readers);
|
|
274 if (readers == 0)
|
|
275 stop.Set();
|
|
276 });
|
|
277 }
|
|
278
|
|
279 stop.WaitOne();
|
|
280
|
|
281 Assert.AreEqual(itemsPerWriter * writersCount, total);
|
|
282 }
|
|
283
|
|
284 [TestMethod]
|
|
285 public void ParallelMapTest() {
|
|
286
|
|
287 const int count = 100000;
|
|
288
|
|
289 var args = new double[count];
|
|
290 var rand = new Random();
|
|
291
|
|
292 for (int i = 0; i < count; i++)
|
|
293 args[i] = rand.NextDouble();
|
|
294
|
|
295 var t = Environment.TickCount;
|
|
296 var res = args.ParallelMap(x => Math.Sin(x*x), 4).Join();
|
|
297
|
|
298 Console.WriteLine("Map complete in {0} ms", Environment.TickCount - t);
|
|
299
|
|
300 t = Environment.TickCount;
|
|
301 for (int i = 0; i < count; i++)
|
|
302 Assert.AreEqual(Math.Sin(args[i] * args[i]), res[i]);
|
|
303 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
304 }
|
|
305
|
|
306 [TestMethod]
|
|
307 public void ChainedMapTest() {
|
|
308
|
81
|
309 using (var pool = new WorkerPool(0,10,1)) {
|
77
|
310 const int count = 10000;
|
|
311
|
|
312 var args = new double[count];
|
|
313 var rand = new Random();
|
|
314
|
|
315 for (int i = 0; i < count; i++)
|
|
316 args[i] = rand.NextDouble();
|
|
317
|
|
318 var t = Environment.TickCount;
|
|
319 var res = args
|
|
320 .ChainedMap(
|
|
321 // Analysis disable once AccessToDisposedClosure
|
|
322 x => pool.Invoke(
|
|
323 () => Math.Sin(x * x)
|
|
324 ),
|
|
325 4
|
|
326 )
|
|
327 .Join();
|
|
328
|
|
329 Console.WriteLine("Map complete in {0} ms", Environment.TickCount - t);
|
|
330
|
|
331 t = Environment.TickCount;
|
|
332 for (int i = 0; i < count; i++)
|
|
333 Assert.AreEqual(Math.Sin(args[i] * args[i]), res[i]);
|
|
334 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
335 Console.WriteLine("Max workers: {0}", pool.MaxRunningThreads);
|
|
336 }
|
|
337 }
|
|
338
|
|
339 [TestMethod]
|
|
340 public void ParallelForEachTest() {
|
|
341
|
|
342 const int count = 100000;
|
|
343
|
|
344 var args = new int[count];
|
|
345 var rand = new Random();
|
|
346
|
|
347 for (int i = 0; i < count; i++)
|
|
348 args[i] = (int)(rand.NextDouble() * 100);
|
|
349
|
|
350 int result = 0;
|
|
351
|
|
352 var t = Environment.TickCount;
|
|
353 args.ParallelForEach(x => Interlocked.Add(ref result, x), 4).Join();
|
|
354
|
|
355 Console.WriteLine("Iteration complete in {0} ms, result: {1}", Environment.TickCount - t, result);
|
|
356
|
|
357 int result2 = 0;
|
|
358
|
|
359 t = Environment.TickCount;
|
|
360 for (int i = 0; i < count; i++)
|
|
361 result2 += args[i];
|
|
362 Assert.AreEqual(result2, result);
|
|
363 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
364 }
|
|
365
|
|
366 [TestMethod]
|
|
367 public void ComplexCase1Test() {
|
|
368 var flags = new bool[3];
|
|
369
|
|
370 // op1 (aync 200ms) => op2 (async 200ms) => op3 (sync map)
|
|
371
|
|
372 var step1 = PromiseHelper
|
|
373 .Sleep(200, "Alan")
|
|
374 .Cancelled(() => flags[0] = true);
|
|
375 var p = step1
|
|
376 .Chain(x =>
|
|
377 PromiseHelper
|
|
378 .Sleep(200, "Hi, " + x)
|
|
379 .Then(y => y)
|
|
380 .Cancelled(() => flags[1] = true)
|
|
381 )
|
|
382 .Cancelled(() => flags[2] = true);
|
|
383 step1.Join();
|
|
384 p.Cancel();
|
|
385 try {
|
|
386 Assert.AreEqual(p.Join(), "Hi, Alan");
|
|
387 Assert.Fail("Shouldn't get here");
|
|
388 } catch (OperationCanceledException) {
|
|
389 }
|
|
390
|
|
391 Assert.IsFalse(flags[0]);
|
|
392 Assert.IsTrue(flags[1]);
|
|
393 Assert.IsTrue(flags[2]);
|
|
394 }
|
|
395
|
|
396 [TestMethod]
|
|
397 public void ChainedCancel1Test() {
|
|
398 // при отмене сцепленной асинхронной операции все обещание должно
|
|
399 // завершаться ошибкой OperationCanceledException
|
|
400 var p = PromiseHelper
|
|
401 .Sleep(1, "Hi, HAL!")
|
|
402 .Then(x => {
|
|
403 // запускаем две асинхронные операции
|
|
404 var result = PromiseHelper.Sleep(1000, "HEM ENABLED!!!");
|
|
405 // вторая операция отменяет первую до завершения
|
|
406 PromiseHelper
|
|
407 .Sleep(100, "HAL, STOP!")
|
|
408 .Then(result.Cancel);
|
|
409 return result;
|
|
410 });
|
|
411 try {
|
|
412 p.Join();
|
|
413 } catch (TargetInvocationException err) {
|
|
414 Assert.IsTrue(err.InnerException is OperationCanceledException);
|
|
415 }
|
|
416 }
|
|
417
|
|
418 [TestMethod]
|
|
419 public void ChainedCancel2Test() {
|
|
420 // при отмене цепочки обещаний, вложенные операции также должны отменяться
|
|
421 var pSurvive = new Promise<bool>();
|
|
422 var hemStarted = new ManualResetEvent(false);
|
|
423 var p = PromiseHelper
|
|
424 .Sleep(1, "Hi, HAL!")
|
|
425 .Chain(x => {
|
|
426 hemStarted.Set();
|
|
427 // запускаем две асинхронные операции
|
|
428 var result = PromiseHelper
|
106
|
429 .Sleep(100000000, "HEM ENABLED!!!")
|
|
430 .Then(s => {
|
|
431 pSurvive.Resolve(false);
|
|
432 return s;
|
|
433 });
|
77
|
434
|
|
435 result
|
|
436 .Cancelled(() => pSurvive.Resolve(true));
|
|
437
|
|
438 return result;
|
|
439 });
|
|
440
|
|
441 hemStarted.WaitOne();
|
|
442 p.Cancel();
|
|
443
|
|
444 try {
|
|
445 p.Join();
|
|
446 } catch (OperationCanceledException) {
|
|
447 Assert.IsTrue(pSurvive.Join());
|
|
448 }
|
|
449 }
|
|
450 }
|
|
451 }
|
|
452
|