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