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]
|
|
142 public void PoolTest() {
|
|
143 var pid = Thread.CurrentThread.ManagedThreadId;
|
|
144 var p = AsyncPool.Invoke(() => Thread.CurrentThread.ManagedThreadId);
|
|
145
|
|
146 Assert.AreNotEqual(pid, p.Join());
|
|
147 }
|
|
148
|
|
149 [TestMethod]
|
|
150 public void WorkerPoolSizeTest() {
|
81
|
151 var pool = new WorkerPool(5, 10, 1);
|
77
|
152
|
|
153 Assert.AreEqual(5, pool.PoolSize);
|
|
154
|
|
155 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
156 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
157 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
158
|
|
159 Assert.AreEqual(5, pool.PoolSize);
|
|
160
|
|
161 for (int i = 0; i < 100; i++)
|
|
162 pool.Invoke(() => { Thread.Sleep(100000000); return 10; });
|
|
163 Thread.Sleep(200);
|
|
164 Assert.AreEqual(10, pool.PoolSize);
|
|
165
|
|
166 pool.Dispose();
|
|
167 }
|
|
168
|
|
169 [TestMethod]
|
|
170 public void WorkerPoolCorrectTest() {
|
|
171 var pool = new WorkerPool(0,1000,100);
|
|
172
|
|
173 const int iterations = 1000;
|
|
174 int pending = iterations;
|
|
175 var stop = new ManualResetEvent(false);
|
|
176
|
|
177 var count = 0;
|
|
178 for (int i = 0; i < iterations; i++) {
|
|
179 pool
|
|
180 .Invoke(() => 1)
|
|
181 .Then(x => Interlocked.Add(ref count, x))
|
|
182 .Then(x => Math.Log10(x))
|
|
183 .Anyway(() => {
|
|
184 Interlocked.Decrement(ref pending);
|
|
185 if (pending == 0)
|
|
186 stop.Set();
|
|
187 });
|
|
188 }
|
|
189
|
|
190 stop.WaitOne();
|
|
191
|
|
192 Assert.AreEqual(iterations, count);
|
|
193 Console.WriteLine("Max threads: {0}", pool.MaxRunningThreads);
|
|
194 pool.Dispose();
|
|
195
|
|
196 }
|
|
197
|
|
198 [TestMethod]
|
|
199 public void WorkerPoolDisposeTest() {
|
|
200 var pool = new WorkerPool(5, 20);
|
|
201 Assert.AreEqual(5, pool.PoolSize);
|
|
202 pool.Dispose();
|
|
203 Thread.Sleep(500);
|
|
204 Assert.AreEqual(0, pool.PoolSize);
|
|
205 pool.Dispose();
|
|
206 }
|
|
207
|
|
208 [TestMethod]
|
|
209 public void MTQueueTest() {
|
|
210 var queue = new MTQueue<int>();
|
|
211 int res;
|
|
212
|
|
213 queue.Enqueue(10);
|
|
214 Assert.IsTrue(queue.TryDequeue(out res));
|
|
215 Assert.AreEqual(10, res);
|
|
216 Assert.IsFalse(queue.TryDequeue(out res));
|
|
217
|
|
218 for (int i = 0; i < 1000; i++)
|
|
219 queue.Enqueue(i);
|
|
220
|
|
221 for (int i = 0; i < 1000; i++) {
|
|
222 queue.TryDequeue(out res);
|
|
223 Assert.AreEqual(i, res);
|
|
224 }
|
|
225
|
|
226 int writers = 0;
|
|
227 int readers = 0;
|
|
228 var stop = new ManualResetEvent(false);
|
|
229 int total = 0;
|
|
230
|
|
231 const int itemsPerWriter = 10000;
|
|
232 const int writersCount = 10;
|
|
233
|
|
234 for (int i = 0; i < writersCount; i++) {
|
|
235 Interlocked.Increment(ref writers);
|
|
236 AsyncPool
|
|
237 .InvokeNewThread(() => {
|
|
238 for (int ii = 0; ii < itemsPerWriter; ii++) {
|
|
239 queue.Enqueue(1);
|
|
240 }
|
|
241 return 1;
|
|
242 })
|
|
243 .Anyway(() => Interlocked.Decrement(ref writers));
|
|
244 }
|
|
245
|
|
246 for (int i = 0; i < 10; i++) {
|
|
247 Interlocked.Increment(ref readers);
|
|
248 AsyncPool
|
|
249 .InvokeNewThread(() => {
|
|
250 int t;
|
|
251 do {
|
|
252 while (queue.TryDequeue(out t))
|
|
253 Interlocked.Add(ref total, t);
|
|
254 } while (writers > 0);
|
|
255 return 1;
|
|
256 })
|
|
257 .Anyway(() => {
|
|
258 Interlocked.Decrement(ref readers);
|
|
259 if (readers == 0)
|
|
260 stop.Set();
|
|
261 });
|
|
262 }
|
|
263
|
|
264 stop.WaitOne();
|
|
265
|
|
266 Assert.AreEqual(itemsPerWriter * writersCount, total);
|
|
267 }
|
|
268
|
|
269 [TestMethod]
|
|
270 public void ParallelMapTest() {
|
|
271
|
|
272 const int count = 100000;
|
|
273
|
|
274 var args = new double[count];
|
|
275 var rand = new Random();
|
|
276
|
|
277 for (int i = 0; i < count; i++)
|
|
278 args[i] = rand.NextDouble();
|
|
279
|
|
280 var t = Environment.TickCount;
|
|
281 var res = args.ParallelMap(x => Math.Sin(x*x), 4).Join();
|
|
282
|
|
283 Console.WriteLine("Map complete in {0} ms", Environment.TickCount - t);
|
|
284
|
|
285 t = Environment.TickCount;
|
|
286 for (int i = 0; i < count; i++)
|
|
287 Assert.AreEqual(Math.Sin(args[i] * args[i]), res[i]);
|
|
288 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
289 }
|
|
290
|
|
291 [TestMethod]
|
|
292 public void ChainedMapTest() {
|
|
293
|
81
|
294 using (var pool = new WorkerPool(0,10,1)) {
|
77
|
295 const int count = 10000;
|
|
296
|
|
297 var args = new double[count];
|
|
298 var rand = new Random();
|
|
299
|
|
300 for (int i = 0; i < count; i++)
|
|
301 args[i] = rand.NextDouble();
|
|
302
|
|
303 var t = Environment.TickCount;
|
|
304 var res = args
|
|
305 .ChainedMap(
|
|
306 // Analysis disable once AccessToDisposedClosure
|
|
307 x => pool.Invoke(
|
|
308 () => Math.Sin(x * x)
|
|
309 ),
|
|
310 4
|
|
311 )
|
|
312 .Join();
|
|
313
|
|
314 Console.WriteLine("Map complete in {0} ms", Environment.TickCount - t);
|
|
315
|
|
316 t = Environment.TickCount;
|
|
317 for (int i = 0; i < count; i++)
|
|
318 Assert.AreEqual(Math.Sin(args[i] * args[i]), res[i]);
|
|
319 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
320 Console.WriteLine("Max workers: {0}", pool.MaxRunningThreads);
|
|
321 }
|
|
322 }
|
|
323
|
|
324 [TestMethod]
|
|
325 public void ParallelForEachTest() {
|
|
326
|
|
327 const int count = 100000;
|
|
328
|
|
329 var args = new int[count];
|
|
330 var rand = new Random();
|
|
331
|
|
332 for (int i = 0; i < count; i++)
|
|
333 args[i] = (int)(rand.NextDouble() * 100);
|
|
334
|
|
335 int result = 0;
|
|
336
|
|
337 var t = Environment.TickCount;
|
|
338 args.ParallelForEach(x => Interlocked.Add(ref result, x), 4).Join();
|
|
339
|
|
340 Console.WriteLine("Iteration complete in {0} ms, result: {1}", Environment.TickCount - t, result);
|
|
341
|
|
342 int result2 = 0;
|
|
343
|
|
344 t = Environment.TickCount;
|
|
345 for (int i = 0; i < count; i++)
|
|
346 result2 += args[i];
|
|
347 Assert.AreEqual(result2, result);
|
|
348 Console.WriteLine("Verified in {0} ms", Environment.TickCount - t);
|
|
349 }
|
|
350
|
|
351 [TestMethod]
|
|
352 public void ComplexCase1Test() {
|
|
353 var flags = new bool[3];
|
|
354
|
|
355 // op1 (aync 200ms) => op2 (async 200ms) => op3 (sync map)
|
|
356
|
|
357 var step1 = PromiseHelper
|
|
358 .Sleep(200, "Alan")
|
|
359 .Cancelled(() => flags[0] = true);
|
|
360 var p = step1
|
|
361 .Chain(x =>
|
|
362 PromiseHelper
|
|
363 .Sleep(200, "Hi, " + x)
|
|
364 .Then(y => y)
|
|
365 .Cancelled(() => flags[1] = true)
|
|
366 )
|
|
367 .Cancelled(() => flags[2] = true);
|
|
368 step1.Join();
|
|
369 p.Cancel();
|
|
370 try {
|
|
371 Assert.AreEqual(p.Join(), "Hi, Alan");
|
|
372 Assert.Fail("Shouldn't get here");
|
|
373 } catch (OperationCanceledException) {
|
|
374 }
|
|
375
|
|
376 Assert.IsFalse(flags[0]);
|
|
377 Assert.IsTrue(flags[1]);
|
|
378 Assert.IsTrue(flags[2]);
|
|
379 }
|
|
380
|
|
381 [TestMethod]
|
|
382 public void ChainedCancel1Test() {
|
|
383 // при отмене сцепленной асинхронной операции все обещание должно
|
|
384 // завершаться ошибкой OperationCanceledException
|
|
385 var p = PromiseHelper
|
|
386 .Sleep(1, "Hi, HAL!")
|
|
387 .Then(x => {
|
|
388 // запускаем две асинхронные операции
|
|
389 var result = PromiseHelper.Sleep(1000, "HEM ENABLED!!!");
|
|
390 // вторая операция отменяет первую до завершения
|
|
391 PromiseHelper
|
|
392 .Sleep(100, "HAL, STOP!")
|
|
393 .Then(result.Cancel);
|
|
394 return result;
|
|
395 });
|
|
396 try {
|
|
397 p.Join();
|
|
398 } catch (TargetInvocationException err) {
|
|
399 Assert.IsTrue(err.InnerException is OperationCanceledException);
|
|
400 }
|
|
401 }
|
|
402
|
|
403 [TestMethod]
|
|
404 public void ChainedCancel2Test() {
|
|
405 // при отмене цепочки обещаний, вложенные операции также должны отменяться
|
|
406 var pSurvive = new Promise<bool>();
|
|
407 var hemStarted = new ManualResetEvent(false);
|
|
408 var p = PromiseHelper
|
|
409 .Sleep(1, "Hi, HAL!")
|
|
410 .Chain(x => {
|
|
411 hemStarted.Set();
|
|
412 // запускаем две асинхронные операции
|
|
413 var result = PromiseHelper
|
|
414 .Sleep(10000, "HEM ENABLED!!!")
|
|
415 .Then(s => pSurvive.Resolve(false));
|
|
416
|
|
417 result
|
|
418 .Cancelled(() => pSurvive.Resolve(true));
|
|
419
|
|
420 return result;
|
|
421 });
|
|
422
|
|
423 hemStarted.WaitOne();
|
|
424 p.Cancel();
|
|
425
|
|
426 try {
|
|
427 p.Join();
|
|
428 } catch (OperationCanceledException) {
|
|
429 Assert.IsTrue(pSurvive.Join());
|
|
430 }
|
|
431 }
|
|
432 }
|
|
433 }
|
|
434
|