-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncEnumerableExtensionTests.cs
More file actions
196 lines (165 loc) · 7.03 KB
/
AsyncEnumerableExtensionTests.cs
File metadata and controls
196 lines (165 loc) · 7.03 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
using System.Diagnostics;
using Xunit.Abstractions;
using Task = System.Threading.Tasks.Task;
namespace Temppus.BatchedAsyncEnumerable.Tests
{
public class AsyncEnumerableExtensionTests(ITestOutputHelper output)
{
private const int SourceItemsCount = 10_000;
private static readonly IEnumerable<int> SourceItems = Enumerable.Range(0, SourceItemsCount);
[Fact]
public async Task Test_Example_Batch_Usage()
{
const int batchSize = 5;
output.WriteLine("Start");
await foreach (var batch in SampleUnderlyingAsyncEnumerable(itemsToGenerate: 12, output)
.ToBatchedAsyncEnumerable(batchSize: batchSize,
batchTimeout: TimeSpan.FromMilliseconds(500),
CancellationToken.None))
{
output.WriteLine($"{DateTime.UtcNow.TimeOfDay:g} - Processing batch of size {batch.Length} for 1 second simulated");
await Task.Delay(TimeSpan.FromMilliseconds(1000));
output.WriteLine($"{DateTime.UtcNow.TimeOfDay:g} - Batch of {batch.Length} processed");
}
output.WriteLine("Done");
return;
static async IAsyncEnumerable<int> SampleUnderlyingAsyncEnumerable(int itemsToGenerate, ITestOutputHelper output)
{
foreach (var sourceItem in Enumerable.Range(0, itemsToGenerate))
{
await Task.Delay(1);
output.WriteLine($"{DateTime.UtcNow.TimeOfDay:g} - Reading underlying item {sourceItem + 1}");
yield return sourceItem;
}
}
}
[Theory]
[InlineData(100, 20)]
[InlineData(100, 100)]
[InlineData(100, 150)]
public async Task Test_Correct_Batching(int batchTimerPeriodMs, int batchProcessingTimeMs)
{
int batchesCount = 0;
var flattenItems = new List<int>();
const int batchSize = 1000;
await foreach (var batch in CreateUnderlyingAsyncEnumerable(true).ToBatchedAsyncEnumerable(
batchSize,
TimeSpan.FromMilliseconds(batchTimerPeriodMs),
CancellationToken.None))
{
var logMessage = $"Batch size: {batch.Length}. From: {batch.First()}, To: {batch.Last()}";
Debug.WriteLine(logMessage);
output.WriteLine(logMessage);
flattenItems.AddRange(batch);
batchesCount++;
await Task.Delay(TimeSpan.FromMilliseconds(batchProcessingTimeMs));
}
Assert.Equal(SourceItemsCount / batchSize, batchesCount);
Assert.True(flattenItems.SequenceEqual(SourceItems));
}
[Theory(Timeout = 5000)]
[InlineData(AsyncTermination.Break)]
[InlineData(AsyncTermination.Cancellation)]
[InlineData(AsyncTermination.ThrowingException)]
public async Task Test_Batching_Termination(AsyncTermination asyncTermination)
{
int batchesCount = 0;
const int batchesToCache = 4;
const int maxBatches = 3;
const int batchSize = 1000;
try
{
var cts = new CancellationTokenSource();
await foreach (var batch in CreateUnderlyingAsyncEnumerable().ToBatchedAsyncEnumerable(
batchSize, batchSize * batchesToCache,
TimeSpan.FromMilliseconds(100),
cts.Token))
{
var logMessage = $"Batch size: {batch.Length}. From: {batch.First()}, To: {batch.Last()}";
Debug.WriteLine(logMessage);
output.WriteLine(logMessage);
batchesCount++;
await Task.Delay(TimeSpan.FromMilliseconds(100), CancellationToken.None);
if (batchesCount >= maxBatches)
{
bool @break = false;
switch (asyncTermination)
{
case AsyncTermination.Break:
@break = true;
break;
case AsyncTermination.Cancellation:
cts.Cancel();
break;
case AsyncTermination.ThrowingException:
throw new InvalidOperationException("UPS");
default:
throw new NotImplementedException();
}
if (@break)
{
break;
}
}
}
}
catch (InvalidOperationException e) when (e.Message == "UPS") { }
if (asyncTermination == AsyncTermination.Cancellation)
{
Assert.True(batchesCount >= maxBatches);
}
else
{
Assert.Equal(maxBatches, batchesCount);
}
}
[Fact]
public async Task Test_Underlying_Enumerable_Throws_And_Propagates()
{
const int batchSize = 10;
const int failOnIdx = 25;
var ex = await Assert.ThrowsAsync<Exception>(async () =>
{
await foreach (var _ in AsyncEnumerableWhichFailsAfter(failOnIdx)
.ToBatchedAsyncEnumerable(batchSize,
TimeSpan.FromMilliseconds(100),
CancellationToken.None))
{
}
});
Assert.Equal($"Simulated underlying exception at idx {failOnIdx}", ex.Message);
}
private static async IAsyncEnumerable<int> CreateUnderlyingAsyncEnumerable(bool itemsAlwaysAvailableSynchronously = false)
{
foreach (var sourceItem in SourceItems)
{
if (itemsAlwaysAvailableSynchronously)
{
yield return sourceItem;
}
else
{
// Simulate also async path (items is not yielded synchronously)
if (sourceItem % 100 == 0)
{
await Task.Delay(1);
}
yield return sourceItem;
}
}
}
private static async IAsyncEnumerable<int> AsyncEnumerableWhichFailsAfter(int failOnIdx = 3)
{
int idx = 0;
while (true)
{
await Task.Delay(1);
if (idx == failOnIdx)
{
throw new Exception($"Simulated underlying exception at idx {failOnIdx}");
}
yield return idx++;
}
}
}
}