-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAsyncEnumerableProcessorTests.cs
More file actions
461 lines (391 loc) · 14.3 KB
/
Copy pathAsyncEnumerableProcessorTests.cs
File metadata and controls
461 lines (391 loc) · 14.3 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EnumerableAsyncProcessor.Extensions;
using System.Runtime.CompilerServices;
using TUnit.Assertions;
using TUnit.Core;
namespace EnumerableAsyncProcessor.UnitTests;
public class AsyncEnumerableProcessorTests
{
private static async IAsyncEnumerable<int> GenerateAsyncEnumerable(int count, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
for (int i = 1; i <= count; i++)
{
await Task.Yield();
cancellationToken.ThrowIfCancellationRequested();
yield return i;
}
}
[Test]
public async Task ForEachAsync_ProcessOneAtATime_ProcessesAllItems()
{
var processedItems = new List<int>();
var asyncEnumerable = GenerateAsyncEnumerable(10);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(10);
lock (processedItems)
{
processedItems.Add(item);
}
})
.ProcessOneAtATime()
.ExecuteAsync();
await Assert.That(processedItems.Count).IsEqualTo(10);
await Assert.That(processedItems).IsEquivalentTo(Enumerable.Range(1, 10));
}
[Test]
public async Task ForEachAsync_ProcessInParallel_ProcessesAllItems()
{
var processedItems = new List<int>();
var asyncEnumerable = GenerateAsyncEnumerable(20);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(10);
lock (processedItems)
{
processedItems.Add(item);
}
})
.ProcessInParallel(5)
.ExecuteAsync();
await Assert.That(processedItems.Count).IsEqualTo(20);
await Assert.That(processedItems.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 20));
}
[Test]
public async Task SelectAsync_ProcessOneAtATime_ReturnsTransformedItems()
{
var asyncEnumerable = GenerateAsyncEnumerable(5);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(10);
return item * 2;
})
.ProcessOneAtATime()
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.Count).IsEqualTo(5);
await Assert.That(results).IsEquivalentTo(new[] { 2, 4, 6, 8, 10 });
}
[Test]
public async Task SelectAsync_ProcessInParallel_ReturnsAllTransformedItems()
{
var asyncEnumerable = GenerateAsyncEnumerable(10);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(10);
return item * 2;
})
.ProcessInParallel(3)
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.Count).IsEqualTo(10);
await Assert.That(results.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 10).Select(x => x * 2));
}
[Test]
public async Task SelectAsync_BoundedParallelism_PreservesInputOrder()
{
var results = await GenerateAsyncEnumerable(20)
.SelectAsync(async item =>
{
await Task.Delay((21 - item) * 2);
return item;
})
.ProcessInParallel(4)
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.SequenceEqual(Enumerable.Range(1, 20))).IsTrue();
}
[Test, Timeout(10_000)]
public async Task BoundedParallelism_AppliesBackpressureToSource(CancellationToken cancellationToken)
{
const int maxConcurrency = 2;
var producedCount = 0;
var startedCount = 0;
var workersStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseWorkers = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
async IAsyncEnumerable<int> Source([EnumeratorCancellation] CancellationToken token = default)
{
for (var i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested();
Interlocked.Increment(ref producedCount);
yield return i;
await Task.Yield();
}
}
var processingTask = Source(cancellationToken)
.ForEachAsync(async _ =>
{
if (Interlocked.Increment(ref startedCount) == maxConcurrency)
{
workersStarted.TrySetResult();
}
await releaseWorkers.Task;
}, cancellationToken)
.ProcessInParallel(maxConcurrency)
.ExecuteAsync();
try
{
await workersStarted.Task.WaitAsync(TimeSpan.FromSeconds(3), cancellationToken);
await Task.Delay(100, cancellationToken);
await Assert.That(producedCount).IsLessThanOrEqualTo((maxConcurrency * 2) + 1);
}
finally
{
releaseWorkers.TrySetResult();
}
await processingTask;
}
[Test]
public async Task ForEachAsync_ProcessInParallel_WithHighConcurrency_HandlesCorrectly()
{
var processedCount = 0;
var asyncEnumerable = GenerateAsyncEnumerable(100);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
Interlocked.Increment(ref processedCount);
})
.ProcessInParallel(50)
.ExecuteAsync();
await Assert.That(processedCount).IsEqualTo(100);
}
[Test]
public async Task SelectAsync_ProcessInParallel_WithHighConcurrency_HandlesCorrectly()
{
var asyncEnumerable = GenerateAsyncEnumerable(50);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(5);
return item * 3;
})
.ProcessInParallel(25)
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.Count).IsEqualTo(50);
await Assert.That(results.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 50).Select(x => x * 3));
}
[Test]
public async Task ForEachAsync_WithCancellation_StopsProcessing()
{
var cts = new CancellationTokenSource();
var processedCount = 0;
var asyncEnumerable = GenerateAsyncEnumerable(100, cts.Token);
var task = asyncEnumerable
.ForEachAsync(async item =>
{
// Check cancellation before processing
if (cts.Token.IsCancellationRequested)
return;
if (item == 10)
{
cts.Cancel();
}
await Task.Delay(10);
// Check cancellation after delay
if (cts.Token.IsCancellationRequested)
return;
Interlocked.Increment(ref processedCount);
}, cts.Token)
.ProcessInParallel(5)
.ExecuteAsync();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
await Assert.That(processedCount).IsLessThan(100);
}
[Test]
public async Task SelectAsync_WithEmptyAsyncEnumerable_ReturnsEmptyResults()
{
var asyncEnumerable = GenerateAsyncEnumerable(0);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(10);
return item * 2;
})
.ProcessInParallel(5)
.ExecuteAsync()
.ToListAsync();
await Assert.That(results).IsEmpty();
}
[Test]
public async Task ForEachAsync_WithException_PropagatesException()
{
var asyncEnumerable = GenerateAsyncEnumerable(10);
var task = asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(10);
if (item == 5)
{
throw new InvalidOperationException("Test exception");
}
})
.ProcessInParallel(3)
.ExecuteAsync();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await task);
await Assert.That(exception!.Message).IsEqualTo("Test exception");
}
[Test, Timeout(10_000)]
public async Task ForEachAsync_WithConcurrentExceptions_PropagatesOriginalException(
CancellationToken cancellationToken)
{
var startedCount = 0;
var workersStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseWorkers = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var task = GenerateAsyncEnumerable(2)
.ForEachAsync(async _ =>
{
if (Interlocked.Increment(ref startedCount) == 2)
{
workersStarted.TrySetResult();
}
await releaseWorkers.Task.WaitAsync(cancellationToken);
throw new InvalidOperationException("Concurrent failure");
})
.ProcessInParallel(2)
.ExecuteAsync();
await workersStarted.Task.WaitAsync(cancellationToken);
releaseWorkers.TrySetResult();
await Assert.ThrowsAsync<InvalidOperationException>(() => task);
}
[Test]
public async Task ForEachAsync_ProcessInParallel_UnboundedConcurrency_ProcessesAllItems()
{
var processedItems = new List<int>();
var asyncEnumerable = GenerateAsyncEnumerable(50);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
lock (processedItems)
{
processedItems.Add(item);
}
})
.ProcessInParallel() // Unbounded concurrency
.ExecuteAsync();
await Assert.That(processedItems.Count).IsEqualTo(50);
await Assert.That(processedItems.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 50));
}
[Test]
public async Task SelectAsync_ProcessInParallel_UnboundedConcurrency_ReturnsAllResults()
{
var asyncEnumerable = GenerateAsyncEnumerable(30);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(5);
return item * 2;
})
.ProcessInParallel() // Unbounded concurrency
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.Count).IsEqualTo(30);
await Assert.That(results.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 30).Select(x => x * 2));
}
[Test]
public async Task ForEachAsync_ProcessInParallel_WithThreadPoolScheduling_ProcessesAllItems()
{
var processedItems = new List<int>();
var asyncEnumerable = GenerateAsyncEnumerable(20);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
lock (processedItems)
{
processedItems.Add(item);
}
})
.ProcessInParallel(scheduleOnThreadPool: true)
.ExecuteAsync();
await Assert.That(processedItems.Count).IsEqualTo(20);
await Assert.That(processedItems.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 20));
}
[Test]
public async Task ForEachAsync_ProcessInBatches_ProcessesAllItemsInBatches()
{
var processedBatches = new List<int>();
var asyncEnumerable = GenerateAsyncEnumerable(25);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
lock (processedBatches)
{
processedBatches.Add(item);
}
})
.ProcessInBatches(5)
.ExecuteAsync();
await Assert.That(processedBatches.Count).IsEqualTo(25);
await Assert.That(processedBatches.OrderBy(x => x)).IsEquivalentTo(Enumerable.Range(1, 25));
}
[Test]
public async Task SelectAsync_ProcessInBatches_ReturnsAllResultsInBatches()
{
var asyncEnumerable = GenerateAsyncEnumerable(23);
var results = await asyncEnumerable
.SelectAsync(async item =>
{
await Task.Delay(5);
return item * 3;
})
.ProcessInBatches(5)
.ExecuteAsync()
.ToListAsync();
await Assert.That(results.Count).IsEqualTo(23);
// Batches maintain order within batch, so results should be in order
await Assert.That(results).IsEquivalentTo(Enumerable.Range(1, 23).Select(x => x * 3));
}
[Test]
public async Task ProcessInParallel_NullableConcurrency_WorksCorrectly()
{
var asyncEnumerable = GenerateAsyncEnumerable(15);
var processedCount = 0;
// Test with null concurrency (unbounded)
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
Interlocked.Increment(ref processedCount);
})
.ProcessInParallel((int?)null)
.ExecuteAsync();
await Assert.That(processedCount).IsEqualTo(15);
// Reset and test with specified concurrency
processedCount = 0;
asyncEnumerable = GenerateAsyncEnumerable(15);
await asyncEnumerable
.ForEachAsync(async item =>
{
await Task.Delay(5);
Interlocked.Increment(ref processedCount);
})
.ProcessInParallel((int?)5)
.ExecuteAsync();
await Assert.That(processedCount).IsEqualTo(15);
}
}
internal static class AsyncEnumerableExtensionsForTests
{
public static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source)
{
var list = new List<T>();
await foreach (var item in source)
{
list.Add(item);
}
return list;
}
}