Skip to content

Commit 51aab24

Browse files
committed
test(metrics): refactor async context tests to use async/await patterns
- Convert test methods from synchronous to async Task return types - Replace CountdownEvent with TaskCompletionSource for async-friendly synchronization - Replace Thread.Sleep with await Task.Delay for non-blocking delays - Replace Task.Run with async lambda expressions for proper async context - Replace ManualResetEventSlim with TaskCompletionSource for event signaling - Use Task.WhenAll instead of Task.WaitAll for async task completion - Use Interlocked.Increment for thread-safe counter management - Improve assertion messages for better test failure diagnostics - Eliminate blocking synchronization primitives in favor of async patterns for better concurrency testing
1 parent ec45f5e commit 51aab24

1 file changed

Lines changed: 22 additions & 22 deletions

File tree

libraries/tests/AWS.Lambda.Powertools.ConcurrencyTests/Metrics/MetricsAsyncContextTests.cs

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,13 @@ private class AsyncContextResult
4242
[InlineData(2)]
4343
[InlineData(3)]
4444
[InlineData(5)]
45-
public void BackgroundTaskMetrics_ShouldNotThrowException(int backgroundTaskCount)
45+
public async Task BackgroundTaskMetrics_ShouldNotThrowException(int backgroundTaskCount)
4646
{
4747
Powertools.Metrics.Metrics.ResetForTest();
4848
Powertools.Metrics.Metrics.SetNamespace("TestNamespace");
4949

5050
var results = new AsyncContextResult[backgroundTaskCount];
51-
var allTasksCompleted = new CountdownEvent(backgroundTaskCount);
51+
var tasks = new Task[backgroundTaskCount];
5252

5353
for (int i = 0; i < backgroundTaskCount; i++)
5454
{
@@ -68,11 +68,11 @@ public void BackgroundTaskMetrics_ShouldNotThrowException(int backgroundTaskCoun
6868
result.ExceptionSource = "MainThread";
6969
}
7070

71-
Task.Run(() =>
71+
tasks[taskIndex] = Task.Run(async () =>
7272
{
7373
try
7474
{
75-
Thread.Sleep(Random.Shared.Next(10, 50));
75+
await Task.Delay(Random.Shared.Next(10, 50));
7676
Powertools.Metrics.Metrics.AddMetric($"background_metric_{taskIndex}", 1, MetricUnit.Count);
7777
Powertools.Metrics.Metrics.AddDimension($"background_dim_{taskIndex}", "value");
7878
result.BackgroundTaskMetricAdded = true;
@@ -83,14 +83,10 @@ public void BackgroundTaskMetrics_ShouldNotThrowException(int backgroundTaskCoun
8383
result.ExceptionMessage = ex.Message;
8484
result.ExceptionSource = "BackgroundTask";
8585
}
86-
finally
87-
{
88-
allTasksCompleted.Signal();
89-
}
9086
});
9187
}
9288

93-
allTasksCompleted.Wait(TimeSpan.FromSeconds(10));
89+
await Task.WhenAll(tasks);
9490

9591
Assert.All(results, r => Assert.False(r.ExceptionThrown, $"{r.ExceptionSource}: {r.ExceptionMessage}"));
9692
Assert.All(results, r => Assert.True(r.MainThreadMetricAdded));
@@ -148,31 +144,36 @@ public async Task AsyncAwaitMetrics_ShouldNotThrowException(int invocationCount)
148144
[InlineData(2)]
149145
[InlineData(3)]
150146
[InlineData(5)]
151-
public void FlushDuringBackgroundWork_ShouldNotThrowException(int backgroundTaskCount)
147+
public async Task FlushDuringBackgroundWork_ShouldNotThrowException(int backgroundTaskCount)
152148
{
153149
Powertools.Metrics.Metrics.ResetForTest();
154150
Powertools.Metrics.Metrics.SetNamespace("TestNamespace");
155151

156-
var backgroundTasksStarted = new CountdownEvent(backgroundTaskCount);
157-
var flushCompleted = new ManualResetEventSlim(false);
152+
var backgroundTasksStarted = new TaskCompletionSource<bool>();
153+
var startedCount = 0;
154+
var flushCompleted = new TaskCompletionSource<bool>();
158155
var backgroundExceptions = new List<Exception>();
159156
Exception? flushException = null;
160157

161158
var backgroundTasks = new Task[backgroundTaskCount];
162159
for (int i = 0; i < backgroundTaskCount; i++)
163160
{
164161
int taskIndex = i;
165-
backgroundTasks[i] = Task.Run(() =>
162+
backgroundTasks[i] = Task.Run(async () =>
166163
{
167164
try
168165
{
169-
backgroundTasksStarted.Signal();
166+
if (Interlocked.Increment(ref startedCount) == backgroundTaskCount)
167+
{
168+
backgroundTasksStarted.TrySetResult(true);
169+
}
170+
170171
int metricCount = 0;
171-
while (!flushCompleted.IsSet && metricCount < 100)
172+
while (!flushCompleted.Task.IsCompleted && metricCount < 100)
172173
{
173174
Powertools.Metrics.Metrics.AddMetric($"bg_metric_{taskIndex}_{metricCount}", metricCount, MetricUnit.Count);
174175
metricCount++;
175-
Thread.Sleep(1);
176+
await Task.Delay(1);
176177
}
177178
}
178179
catch (Exception ex)
@@ -182,21 +183,20 @@ public void FlushDuringBackgroundWork_ShouldNotThrowException(int backgroundTask
182183
});
183184
}
184185

185-
var tasksStartedOk = backgroundTasksStarted.Wait(TimeSpan.FromSeconds(10));
186+
var tasksStartedOk = await Task.WhenAny(backgroundTasksStarted.Task, Task.Delay(TimeSpan.FromSeconds(10))) == backgroundTasksStarted.Task;
186187

187188
try
188189
{
189190
Powertools.Metrics.Metrics.AddMetric("main_metric", 1, MetricUnit.Count);
190-
Thread.Sleep(10);
191+
await Task.Delay(10);
191192
Powertools.Metrics.Metrics.Flush();
192193
}
193194
catch (Exception ex) { flushException = ex; }
194-
finally { flushCompleted.Set(); }
195+
finally { flushCompleted.TrySetResult(true); }
195196

196-
var tasksCompletedOk = Task.WaitAll(backgroundTasks, TimeSpan.FromSeconds(10));
197+
await Task.WhenAll(backgroundTasks).WaitAsync(TimeSpan.FromSeconds(10));
197198

198-
Assert.True(tasksStartedOk);
199-
Assert.True(tasksCompletedOk);
199+
Assert.True(tasksStartedOk, "Background tasks did not start in time");
200200
Assert.Null(flushException);
201201
Assert.Empty(backgroundExceptions);
202202
}

0 commit comments

Comments
 (0)