-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathRetryHelper.cs
More file actions
98 lines (81 loc) · 3.09 KB
/
Copy pathRetryHelper.cs
File metadata and controls
98 lines (81 loc) · 3.09 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
using TUnit.Core;
namespace TUnit.Engine.Services.TestExecution;
internal static class RetryHelper
{
private static readonly Task<bool> s_shouldRetryTrue = Task.FromResult(true);
private static readonly Task<bool> s_shouldRetryFalse = Task.FromResult(false);
public static async Task ExecuteWithRetry(TestContext testContext, Func<ValueTask> action)
{
var maxRetries = testContext.Metadata.TestDetails.RetryLimit;
for (var attempt = 0; attempt < maxRetries + 1; attempt++)
{
testContext.CurrentRetryAttempt = attempt;
try
{
await action();
return;
}
catch (Exception ex)
{
if (attempt >= maxRetries)
{
throw;
}
if (await ShouldRetry(testContext, ex, attempt))
{
#if NET
// Stop the failed attempt's activity before retrying
var activity = testContext.Activity;
if (activity is not null)
{
activity.SetTag("test.case.result.status", "fail");
activity.SetTag("tunit.test.retry_attempt", attempt);
TUnitActivitySource.RecordException(activity, ex);
TUnitActivitySource.StopActivity(activity);
testContext.Activity = null;
}
#endif
// Apply backoff delay before retrying
await ApplyBackoffDelay(testContext, attempt).ConfigureAwait(false);
// Clear the previous result before retrying
testContext.Execution.Result = null;
testContext.TestStart = null;
testContext.Execution.TestEnd = null;
#pragma warning disable CS0618 // Obsolete Timing API
testContext.Timings.Clear();
#pragma warning restore CS0618
continue;
}
throw;
}
}
}
private static Task<bool> ShouldRetry(TestContext testContext, Exception ex, int attempt)
{
if (attempt >= testContext.Metadata.TestDetails.RetryLimit)
{
return s_shouldRetryFalse;
}
if (testContext.RetryFunc == null)
{
// Default behavior: retry on any exception if within retry limit
return s_shouldRetryTrue;
}
return testContext.RetryFunc(testContext, ex, attempt + 1);
}
private static Task ApplyBackoffDelay(TestContext testContext, int attempt)
{
var backoffMs = testContext.Metadata.TestDetails.RetryBackoffMs;
if (backoffMs <= 0)
{
return Task.CompletedTask;
}
var multiplier = testContext.Metadata.TestDetails.RetryBackoffMultiplier;
var delayMs = (int)(backoffMs * Math.Pow(multiplier, attempt));
if (delayMs > 0)
{
return Task.Delay(delayMs, testContext.CancellationToken);
}
return Task.CompletedTask;
}
}