Skip to content

Commit a7f3466

Browse files
authored
Document and test custom retry extensibility (#10703)
Copilot-Session: 6c395fb2-fa21-44b2-bc6a-c8d86e197a0b
1 parent 0b3d85c commit a7f3466

6 files changed

Lines changed: 228 additions & 5 deletions

File tree

‎docs/glossary.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,23 @@ An MTP class (`Microsoft.Testing.Platform.Extensions.Messages.PropertyBag`) that
453453

454454
### Retry
455455

456-
An MTP extension (`Microsoft.Testing.Extensions.Retry`) that automatically re-runs failed tests a configurable number of times. Useful for reducing flakiness in CI environments.
456+
An MTP extension (`Microsoft.Testing.Extensions.Retry`) that automatically re-runs failed tests a configurable number of times by restarting the test host and filtering each new run to the tests that failed previously. It is independent from MSTest's in-process [`RetryAttribute`](#retryattribute) and [`RetryBaseAttribute`](#retrybaseattribute). When both mechanisms are enabled, their attempt counts multiply: a test using `[Retry(n)]` can run up to `(n + 1) * (--retry-failed-tests + 1)` times, so avoid combining them unless that is intended.
457+
458+
### RetryAttribute
459+
460+
An MSTest attribute (`Microsoft.VisualStudio.TestTools.UnitTesting.RetryAttribute`) that retries a failed or timed-out test within the same test-host run. It can be applied to a test method or test class and supports a maximum retry count, a delay between attempts, and constant or exponential backoff. It derives from [`RetryBaseAttribute`](#retrybaseattribute), which can be used to implement a custom retry policy. See also the process-level [`Microsoft.Testing.Extensions.Retry`](#retry) extension.
461+
462+
### RetryBaseAttribute
463+
464+
An MSTest extensibility point (`Microsoft.VisualStudio.TestTools.UnitTesting.RetryBaseAttribute`) for implementing custom in-process retry policies. A derived attribute overrides the experimental `[Experimental("MSTESTEXP")]` method `ExecuteAsync(RetryContext)`, inspects the initial failed results, invokes the supplied test delegate for each retry attempt, and returns every attempt in a [`RetryResult`](#retryresult). The implementation owns the retry loop and decides when to stop. The attribute can be applied to a test method or test class; a method-level attribute takes precedence over a class-level attribute, and class-level attributes are not inherited.
465+
466+
### RetryContext
467+
468+
An experimental MSTest structure (`Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext`, `[Experimental("MSTESTEXP")]`) passed to `RetryBaseAttribute.ExecuteAsync`. `FirstRunResults` contains the results from the initial failed or timed-out execution, and `ExecuteTaskGetter` re-executes the test and returns the next attempt's results. See also [`RetryBaseAttribute`](#retrybaseattribute) and [`RetryResult`](#retryresult).
469+
470+
### RetryResult
471+
472+
An experimental MSTest class (`Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult`, `[Experimental("MSTESTEXP")]`) used by custom [`RetryBaseAttribute`](#retrybaseattribute) implementations to return retry attempts in execution order through `AddResult`. `AllResults` exposes every added attempt. Under Microsoft.Testing.Platform, earlier attempts are reported as superseded and the last attempt determines the test outcome; VSTest receives only the final attempt.
457473

458474
### RFC
459475

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.RunSingleTest.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
@@ -348,7 +348,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(
348348
/// consumers that collapse per test node uid keep observing the test's real outcome.
349349
/// </para>
350350
/// </remarks>
351-
private static TestResult[] CombineRetryAttempts(TestResult[] firstAttempt, RetryResult retryResult)
351+
internal static TestResult[] CombineRetryAttempts(TestResult[] firstAttempt, RetryResult retryResult)
352352
{
353353
IReadOnlyList<TestResult[]> retryAttempts = retryResult.AllResults;
354354
if (retryAttempts.Count == 0)

‎src/Adapter/MSTestAdapter.PlatformServices/InternalAPI/InternalAPI.Unshipped.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestDepe
116116
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ParameterMetadataScanCount.get -> int
117117
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ResetParameterMetadataCacheForTesting() -> void
118118
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.SetParameterMetadataScanCallbackForTesting(System.Action? callback) -> void
119+
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.UnitTestRunner.CombineRetryAttempts(Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! firstAttempt, Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult! retryResult) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]!
119120
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.UnitTestRunner.CreateLiveOutputWriter(System.IO.Stream! standardOutput, System.Text.Encoding! encoding) -> System.IO.TextWriter!
120121
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers.RuntimeContext.IsMultiThreaded.get -> bool
121122
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscovererHelpers.GetSettingsExceptionMessage(Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.AdapterSettingsException! ex) -> string!

‎src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ This package extends Microsoft.Testing.Platform with:
2121

2222
Configure retry using `--retry-failed-tests <retries>`, and optionally limit retries with `--retry-failed-tests-max-percentage` or `--retry-failed-tests-max-tests`, or add a delay between retries with `--retry-failed-tests-delay` (e.g. `1s`, `2.5m`, `1h`).
2323

24+
This extension restarts the test host for each retry. It is independent from MSTest's in-process `RetryAttribute` and custom `RetryBaseAttribute` implementations. When both mechanisms are enabled, their attempt counts multiply: a test using `[Retry(n)]` can run up to `(n + 1) * (--retry-failed-tests + 1)` times.
25+
2426
## Documentation
2527

2628
For this extension, see <https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-retry>.

‎test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RetryTests.cs‎

Lines changed: 161 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using Microsoft.Testing.Platform.Acceptance.IntegrationTests;
@@ -167,6 +167,166 @@ public static void ClassCleanup()
167167
public TestContext TestContext { get; set; }
168168
}
169169

170+
[TestClass]
171+
public sealed class CustomRetryTests : AcceptanceTestBase<CustomRetryTests.TestAssetFixture>
172+
{
173+
[TestMethod]
174+
public async Task CustomRetryBaseAttribute_ControlsRetriesAndReportsEveryAttempt()
175+
{
176+
var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, TargetFrameworks.NetCurrent);
177+
string markerDirectory = Path.Combine(Path.GetTempPath(), "mstest-custom-retry-" + Guid.NewGuid().ToString("N"));
178+
Directory.CreateDirectory(markerDirectory);
179+
180+
try
181+
{
182+
TestHostResult testHostResult = await testHost.ExecuteAsync(
183+
environmentVariables: new() { [TestAssetFixture.MarkerDirectoryEnvVar] = markerDirectory },
184+
cancellationToken: TestContext.CancellationToken);
185+
186+
testHostResult.AssertExitCodeIs(ExitCode.Success);
187+
testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0);
188+
testHostResult.AssertOutputContains("failed (try 1) FailsTwiceThenPasses");
189+
testHostResult.AssertOutputContains("failed (try 2) FailsTwiceThenPasses");
190+
testHostResult.AssertOutputContains("retried:");
191+
testHostResult.AssertOutputContains("flaky: 1");
192+
193+
string markerFile = Path.Combine(markerDirectory, TestAssetFixture.MarkerFileName);
194+
Assert.IsTrue(
195+
File.Exists(markerFile),
196+
$"Custom retry marker file not found. StandardOutput:\n{testHostResult.StandardOutput}");
197+
198+
string[] observations = File.ReadAllLines(markerFile);
199+
Assert.Contains("TestExecutions=3", observations);
200+
Assert.Contains("ExecuteAsyncCalls=1", observations);
201+
Assert.Contains("ExecuteTaskGetterCalls=2", observations);
202+
Assert.Contains("FirstRunResultCount=1", observations);
203+
Assert.Contains("FirstRunOutcome=Failed", observations);
204+
}
205+
finally
206+
{
207+
try
208+
{
209+
Directory.Delete(markerDirectory, recursive: true);
210+
}
211+
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
212+
{
213+
// Best-effort cleanup of the temporary marker directory.
214+
}
215+
}
216+
}
217+
218+
public sealed class TestAssetFixture() : TestAssetFixtureBase()
219+
{
220+
public const string ProjectName = "CustomRetryTests";
221+
222+
public const string MarkerDirectoryEnvVar = "CUSTOMRETRY_MARKER_DIR";
223+
224+
public const string MarkerFileName = "custom-retry.marker";
225+
226+
public string ProjectPath => GetAssetPath(ProjectName);
227+
228+
public override (string ID, string Name, string Code) GetAssetsToGenerate() => (ProjectName, ProjectName,
229+
SourceCode
230+
.PatchTargetFrameworks(TargetFrameworks.NetCurrent)
231+
.PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)
232+
.PatchCodeWithReplace("$MarkerDirectoryEnvVar$", MarkerDirectoryEnvVar)
233+
.PatchCodeWithReplace("$MarkerFileName$", MarkerFileName));
234+
235+
private const string SourceCode = """
236+
#file CustomRetryTests.csproj
237+
<Project Sdk="Microsoft.NET.Sdk">
238+
239+
<PropertyGroup>
240+
<OutputType>Exe</OutputType>
241+
<EnableMSTestRunner>true</EnableMSTestRunner>
242+
<TargetFrameworks>$TargetFrameworks$</TargetFrameworks>
243+
</PropertyGroup>
244+
245+
<ItemGroup>
246+
<PackageReference Include="MSTest.TestAdapter" Version="$MSTestVersion$" />
247+
<PackageReference Include="MSTest.TestFramework" Version="$MSTestVersion$" />
248+
</ItemGroup>
249+
</Project>
250+
251+
#file UnitTest1.cs
252+
#pragma warning disable MSTESTEXP
253+
254+
using System;
255+
using System.IO;
256+
using System.Threading.Tasks;
257+
using Microsoft.VisualStudio.TestTools.UnitTesting;
258+
259+
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
260+
public sealed class RetryTwiceAttribute : RetryBaseAttribute
261+
{
262+
public static int ExecuteAsyncCalls { get; private set; }
263+
264+
public static int ExecuteTaskGetterCalls { get; private set; }
265+
266+
public static int FirstRunResultCount { get; private set; }
267+
268+
public static UnitTestOutcome FirstRunOutcome { get; private set; }
269+
270+
protected override async Task<RetryResult> ExecuteAsync(RetryContext retryContext)
271+
{
272+
ExecuteAsyncCalls++;
273+
FirstRunResultCount = retryContext.FirstRunResults.Length;
274+
FirstRunOutcome = retryContext.FirstRunResults[0].Outcome;
275+
276+
var retryResult = new RetryResult();
277+
for (int i = 0; i < 2; i++)
278+
{
279+
ExecuteTaskGetterCalls++;
280+
retryResult.AddResult(await retryContext.ExecuteTaskGetter());
281+
}
282+
283+
return retryResult;
284+
}
285+
}
286+
287+
[TestClass]
288+
public class CustomRetryTestClass
289+
{
290+
private static int _testExecutions;
291+
292+
[TestMethod]
293+
[RetryTwice]
294+
public void FailsTwiceThenPasses()
295+
{
296+
_testExecutions++;
297+
if (_testExecutions < 3)
298+
{
299+
Assert.Fail($"Custom failure from execution {_testExecutions}");
300+
}
301+
}
302+
303+
[ClassCleanup]
304+
public static void ClassCleanup()
305+
{
306+
string markerDirectory = Environment.GetEnvironmentVariable("$MarkerDirectoryEnvVar$");
307+
if (string.IsNullOrEmpty(markerDirectory))
308+
{
309+
return;
310+
}
311+
312+
File.WriteAllLines(
313+
Path.Combine(markerDirectory, "$MarkerFileName$"),
314+
new[]
315+
{
316+
$"TestExecutions={_testExecutions}",
317+
$"ExecuteAsyncCalls={RetryTwiceAttribute.ExecuteAsyncCalls}",
318+
$"ExecuteTaskGetterCalls={RetryTwiceAttribute.ExecuteTaskGetterCalls}",
319+
$"FirstRunResultCount={RetryTwiceAttribute.FirstRunResultCount}",
320+
$"FirstRunOutcome={RetryTwiceAttribute.FirstRunOutcome}",
321+
});
322+
}
323+
}
324+
""";
325+
}
326+
327+
public TestContext TestContext { get; set; }
328+
}
329+
170330
[TestClass]
171331
public sealed class ClassLevelRetryTests : AcceptanceTestBase<ClassLevelRetryTests.TestAssetFixture>
172332
{

‎test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using AwesomeAssertions;
@@ -93,6 +93,50 @@ public async Task RunSingleTestShouldThrowIfTestRunParametersIsNull()
9393
await func.Should().ThrowAsync<ArgumentNullException>();
9494
}
9595

96+
public void CombineRetryAttempts_WhenRetriesProduceResults_FlattensAndTagsAttempts()
97+
{
98+
var initialFailure = new TestResult { Outcome = UnitTestOutcome.Failed };
99+
var firstRetryFailure = new TestResult { Outcome = UnitTestOutcome.Timeout };
100+
var finalSuccess = new TestResult { Outcome = UnitTestOutcome.Passed };
101+
var retryResult = new RetryResult();
102+
retryResult.AddResult([firstRetryFailure]);
103+
retryResult.AddResult([finalSuccess]);
104+
105+
TestResult[] combined = UnitTestRunner.CombineRetryAttempts([initialFailure], retryResult);
106+
107+
combined.Should().Equal(initialFailure, firstRetryFailure, finalSuccess);
108+
combined.Select(result => result.RetryAttemptNumber).Should().Equal(1, 2, 3);
109+
combined.Select(result => result.IsSupersededRetryAttempt).Should().Equal(true, true, false);
110+
}
111+
112+
public void CombineRetryAttempts_WhenLastRetryProducesNoResults_ReturnsEmptyResult()
113+
{
114+
var initialFailure = new TestResult { Outcome = UnitTestOutcome.Failed };
115+
var retryFailure = new TestResult { Outcome = UnitTestOutcome.Failed };
116+
var retryResult = new RetryResult();
117+
retryResult.AddResult([retryFailure]);
118+
retryResult.AddResult([]);
119+
120+
TestResult[] combined = UnitTestRunner.CombineRetryAttempts([initialFailure], retryResult);
121+
122+
combined.Should().BeEmpty();
123+
// The empty final attempt returns before tagging, so the supplied results must remain unchanged.
124+
initialFailure.IsSupersededRetryAttempt.Should().BeFalse();
125+
retryFailure.IsSupersededRetryAttempt.Should().BeFalse();
126+
}
127+
128+
public void CombineRetryAttempts_WhenRetryProducesNoAttempts_ThrowsUnreachableException()
129+
{
130+
Action act = () => UnitTestRunner.CombineRetryAttempts(
131+
[new TestResult { Outcome = UnitTestOutcome.Failed }],
132+
new RetryResult());
133+
134+
Exception exception = act.Should().Throw<Exception>().Which;
135+
// UnreachableException is an internal, per-assembly polyfill on non-NETCOREAPP TFMs, so a generic type
136+
// assertion would compare the adapter's copy with this test assembly's copy and fail on type identity.
137+
exception.GetType().FullName.Should().Be("System.Diagnostics.UnreachableException");
138+
}
139+
96140
public async Task RunSingleTestShouldReturnTestResultIndicateATestNotFoundIfTestMethodCannotBeFound()
97141
{
98142
TestMethod testMethod = CreateTestMethod("M", "C", "A", displayName: null);

0 commit comments

Comments
 (0)