Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions samples/public/WinUIMtpPackagedApp/Probe-Extensions.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,18 @@ try {
}

if ($probe.Name -eq 'retry') {
$attempts = @(Get-ChildItem -LiteralPath (Join-Path $directory 'Retries') -Filter retry.trx -Recurse | Sort-Object FullName)
if ($attempts.Count -ne 2) {
throw 'Expected exactly two retry attempts.'
$attempts = @(Get-ChildItem -LiteralPath (Join-Path $directory 'Retries') -Filter retry.trx -File -Recurse)
if ($attempts.Count -ne 1 -or $attempts[0].Directory.Name -cne '1') {
throw 'Expected exactly one retained first-attempt TRX under Retries.'
}

$finalAttemptTrx = Join-Path $attempts[0].Directory.Parent.FullName '2\retry.trx'
$reports = @(Get-ChildItem -LiteralPath $directory -Filter '*.trx' -File -Recurse)
if ($reports.Count -ne 2 -or (Test-Path -LiteralPath $finalAttemptTrx -PathType Leaf)) {
throw 'Expected exactly two TRX reports with no duplicate final-attempt report under Retries.'
}

Assert-SelectedTrx -Path $attempts[0].FullName -TestName $testName -Outcome 'Failed'
Assert-SelectedTrx -Path $attempts[1].FullName -TestName $testName
}

$status = 'Verified'
Expand Down
2 changes: 1 addition & 1 deletion samples/public/WinUIMtpPackagedApp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ Verification deliberately has boundaries:

- Coverage requires covered lines from the sample, not merely a nonempty Cobertura file or its misleading aggregate `line-rate`. Current packaged execution records no sample coverage and is reported as `Partial`; the script intentionally exits nonzero after writing all results.
- HangDump is enabled during a passing run; no hang is induced and no dump is claimed.
- Retry selects `RetryFailsFirstAttempt`, which fails attempt 1 and passes attempt 2; both attempt TRXs are checked.
- Retry selects `RetryFailsFirstAttempt`, which fails attempt 1 and passes attempt 2. The failed report remains under `Retries/<id>/1/retry.trx`, and the final passed report is at the results root. The probe checks exactly two TRX reports and rejects a duplicate final-attempt report under `Retries`.
- Hot Reload is installed but its interactive watch/restart behavior is not exercised.
- Fakes is included by the profile; no shim assembly is generated or executed, and real Fakes usage requires the applicable Visual Studio Enterprise tooling/license.
- OpenTelemetry's diagnostics producer is enabled, but no exporter/backend is configured. See [MTPOTel](../MTPOTel) for an exporter composition sample.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Testing.Extensions.PackagedApp.Resources;
using Microsoft.Testing.Platform.CommandLine;
using Microsoft.Testing.Platform.Helpers;
using Microsoft.Testing.Platform.IPC;

namespace Microsoft.Testing.Extensions.PackagedApp;

Expand Down Expand Up @@ -97,6 +98,7 @@ internal static (string[] Arguments, bool IsInformationalRequest) Configure(
if (transportIndex >= 0 || !isRestart)
{
setEnvironmentVariable(NativePipeEnvironmentVariable, transportIndex < 0 ? null : remaining[transportIndex + 3]);
setEnvironmentVariable(DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable, transportIndex < 0 ? null : remaining[transportIndex + 3]);
}

if (transportIndex >= 0 && getEnvironmentVariable(ExecutionIdEnvironmentVariable) is null or "")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Testing.Platform.Extensions.TestHostControllers;
using Microsoft.Testing.Platform.IPC;

namespace Microsoft.Testing.Extensions.PackagedApp;

Expand Down Expand Up @@ -30,6 +31,8 @@ internal sealed partial class PackagedAppTestHostLauncher
|| string.Equals(environmentVariable.Key, JUnitReportJournalEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, RetryAttemptEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, RetryRecoveredArtifactManifestEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, LogicalRunIdEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, AppModelControllerExtensionsEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(environmentVariable.Key, TrxTestRunIdEnvironmentVariableName, StringComparison.OrdinalIgnoreCase)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ private static ITestHostHandle LaunchLooseLayout(TestHostLaunchContext context,
// recursively creating another controller/deployment layer when the parent was opted in with "always".
startInfo.Environment[LauncherModeEnvironmentVariable] = NeverMode;
startInfo.Environment.Remove(PackagedAppControllerArguments.NativePipeEnvironmentVariable);
startInfo.Environment.Remove(Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable);

Process process = Process.Start(startInfo)
?? throw new InvalidOperationException($"Failed to start deployed packaged-app test host '{deployedFileName}'.");
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
#nullable enable
static Microsoft.Testing.Extensions.Policy.RetryArtifactProcessor.GetDeferredTrxArtifactDirectory(string! retryRootDirectory) -> string!
static Microsoft.Testing.Extensions.Policy.RetryArtifactProcessor.PublishDeferredTrxArtifactsAsync(System.IServiceProvider! serviceProvider, string! retryRootDirectory, System.Collections.Generic.IReadOnlyDictionary<string!, string!>! movedArtifacts) -> System.Threading.Tasks.Task!
static Microsoft.Testing.Extensions.Policy.RetryTestHostRunner.RunAttemptAsync(System.IServiceProvider! serviceProvider, Microsoft.Testing.Platform.Extensions.OutputDevice.IOutputDeviceDataProducer! producer, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.Logging.ILogger! logger, Microsoft.Testing.Extensions.Policy.RetryFailedTestsPipeServer! retryFailedTestsPipeServer, Microsoft.Testing.Platform.Services.ExecutableInfo! executableInfo, System.Collections.Generic.List<string!>! finalArguments, string? currentTryResultFolder, int attemptCount, int userMaxRetryCount, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.Testing.Extensions.Policy.RetryTestHostRunner.AttemptResult>!
static Microsoft.Testing.Extensions.Policy.RetrySummaryReporter.MoveArtifactsAsync(Microsoft.Testing.Platform.Extensions.OutputDevice.IOutputDeviceDataProducer! producer, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.Logging.ILogger! logger, string! currentTryResultFolder, string! resultDirectory, System.Collections.Generic.IReadOnlyDictionary<string!, string!>! replacements, System.Collections.Generic.IReadOnlyCollection<string!>! trxReportPaths, System.Func<string!, string!, System.Threading.Tasks.Task!>? onTrxMoved, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
6 changes: 6 additions & 0 deletions src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ Configure retry using `--retry-failed-tests <retries>`, and optionally limit ret

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.

When `--report-trx` uses its default filename or a relative `.trx` filename, earlier attempts' TRX reports remain under `Retries/<id>/<attempt>/`, and the final attempt's TRX report is moved to the configured results directory. Collect these attempt reports with `**/*.trx` recursively from that directory to include every physical attempt exactly once. The top-level TRX represents only the final attempt, which may contain just the tests selected for retry; publishing only that file can omit tests that passed earlier. An absolute report filename keeps its explicitly configured location.

Only identified TRX report artifacts are moved. Test attachments remain at their recorded paths, even when their filenames end in `.trx`, so reports such as CTRF can still reference them.

If the .NET SDK also performs artifact post-processing and writes an additional merged report, publish either that merged report or its input reports, not both.

## Documentation

For this extension, see <https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-retry>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,83 @@
// Licensed under dual-license. See LICENSE.PLATFORMTOOLS.txt file in the project root for full license information.

using Microsoft.Testing.Extensions.Policy.Resources;
using Microsoft.Testing.Platform;
using Microsoft.Testing.Platform.Extensions.ArtifactPostProcessing;
using Microsoft.Testing.Platform.Extensions.OutputDevice;
using Microsoft.Testing.Platform.Extensions.RetryFailedTests.Serializers;
using Microsoft.Testing.Platform.Helpers;
using Microsoft.Testing.Platform.IPC;
using Microsoft.Testing.Platform.IPC.Models;
using Microsoft.Testing.Platform.Logging;
using Microsoft.Testing.Platform.OutputDevice;
using Microsoft.Testing.Platform.ServerMode;
using Microsoft.Testing.Platform.Services;

namespace Microsoft.Testing.Extensions.Policy;

internal static class RetryArtifactProcessor
{
public static string GetDeferredTrxArtifactDirectory(string retryRootDirectory)
=> Path.Combine(retryRootDirectory, "ArtifactMetadata");

[UnsupportedOSPlatform("browser")]
public static async Task PublishDeferredTrxArtifactsAsync(
IServiceProvider serviceProvider,
string retryRootDirectory,
IReadOnlyDictionary<string, string> movedArtifacts)
{
IPushOnlyProtocol? protocol = serviceProvider.GetServiceInternal<IPushOnlyProtocol>();
IEnvironment environment = serviceProvider.GetEnvironment();
string? replayPipe = environment.GetEnvironmentVariable(DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable);
string directory = GetDeferredTrxArtifactDirectory(retryRootDirectory);
if ((protocol is not { IsServerMode: true } && replayPipe is not { Length: > 0 }) || !Directory.Exists(directory))
{
return;
}

foreach (string manifest in Directory.GetFiles(directory, "*.bin", SearchOption.TopDirectoryOnly))
{
FileArtifactMessages message = DotnetTestDataConsumer.ReadDeferredTrxArtifacts(manifest);

FileArtifactMessage[] artifacts =
[
.. message.FileArtifacts.Select(artifact =>
{
ApplicationStateGuard.Ensure(
artifact.FullPath is not null
&& PathContainment.IsUnderDirectory(artifact.FullPath, retryRootDirectory));
return movedArtifacts.TryGetValue(Path.GetFullPath(artifact.FullPath), out string? destination)
? artifact with { FullPath = destination }
: artifact;
}),
];
FileArtifactMessages updated = message with { FileArtifacts = artifacts };
if (protocol is { IsServerMode: true })
{
await protocol.SendMessageAsync(updated).ConfigureAwait(false);
}
else
{
#if NET8_0_OR_GREATER
if (OperatingSystem.IsWasi())
{
throw new PlatformNotSupportedException("Retry artifact replay through a named pipe is not supported on WASI.");
}
#endif

await DotnetTestConnection.SendFileArtifactsToPipeAsync(
replayPipe!,
updated,
environment,
serviceProvider.GetTestApplicationCancellationTokenSource().CancellationToken).ConfigureAwait(false);
}

File.Delete(manifest);
}

Directory.Delete(directory, recursive: true);
}

public static IReadOnlyList<RetryAttemptArtifact> SnapshotAttemptArtifacts(
IFileSystem fileSystem,
IReadOnlyList<ArtifactRequest> artifacts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,10 @@ public async Task<int> OrchestrateTestHostExecutionAsync(CancellationToken cance
bool willRetry = attemptCount < userMaxRetryCount + 1;
if (willRetry)
{
await RetryArtifactProcessor.PublishDeferredTrxArtifactsAsync(
_serviceProvider,
retryRootFolder,
new Dictionary<string, string>()).ConfigureAwait(false);
await outputDevice.DisplayAsync(
this,
new FormattedTextOutputDeviceData(string.Format(CultureInfo.CurrentCulture, ExtensionResources.RetryAttemptFailedWillRetry, attemptCount, userMaxRetryCount + 1, failedThisAttempt))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under dual-license. See LICENSE.PLATFORMTOOLS.txt file in the project root for full license information.

using System.Runtime.ExceptionServices;

using Microsoft.Testing.Extensions.Policy.Resources;
using Microsoft.Testing.Platform;
using Microsoft.Testing.Platform.CommandLine;
Expand Down Expand Up @@ -133,6 +135,7 @@ await LogResponseFileFallbackWarningAsync(
retryFailedTestsPipeServer,
executableInfo,
finalArguments,
currentTryResultFolder,
attemptCount,
userMaxRetryCount,
cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -207,20 +210,54 @@ private async Task ProcessArtifactsAsync(
postProcessingDirectory,
cancellationToken).ConfigureAwait(false);

await RetrySummaryReporter.MoveArtifactsAsync(
this,
outputDevice,
fileSystem,
logger,
currentTryResultFolder,
resultDirectory,
replacements,
cancellationToken).ConfigureAwait(false);
RetryArtifactProcessor.PublishExternalArtifacts(
fileSystem,
attemptArtifacts,
attemptCount,
replacements);
Dictionary<string, string> movedArtifacts = [with(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)];
ExceptionDispatchInfo? publicationFailure = null;
try
{
await RetrySummaryReporter.MoveArtifactsAsync(
this,
outputDevice,
fileSystem,
logger,
currentTryResultFolder,
resultDirectory,
replacements,
[.. attemptArtifacts
.Where(artifact => artifact.Attempt == attemptCount && artifact.Kind == "microsoft.testing.trx")
.Select(artifact => artifact.Path)],
(source, destination) =>
{
movedArtifacts[Path.GetFullPath(source)] = destination;
return Task.CompletedTask;
},
cancellationToken).ConfigureAwait(false);
RetryArtifactProcessor.PublishExternalArtifacts(
fileSystem,
attemptArtifacts,
attemptCount,
replacements);
}
catch (Exception ex)
{
publicationFailure = ExceptionDispatchInfo.Capture(ex);
}

try
{
await RetryArtifactProcessor.PublishDeferredTrxArtifactsAsync(
_serviceProvider,
Path.GetDirectoryName(currentTryResultFolder)!,
movedArtifacts).ConfigureAwait(false);
}
catch (Exception ex) when (publicationFailure is not null)
{
await logger.LogWarningAsync($"Failed to replay retry artifacts after publication failed: {ex}").ConfigureAwait(false);
}
finally
{
publicationFailure?.Throw();
}
}
finally
{
Expand Down
Loading
Loading