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