From 05fb9f8860f3a9cbba6acb3082b8507a03c9bfe9 Mon Sep 17 00:00:00 2001 From: Copilot Date: Mon, 9 Nov 2026 15:35:34 +0100 Subject: [PATCH] Backport single-publication Retry TRX reports to rel/4.5 Adapt #12241 (f76d4524b917e64d6fd93a2cce35ecf1ec6440f6) across Core, Retry, TRX and both release PackagedApp controller layouts. Preserve compatibility overloads, release framework assets and existing SDK wire models; retain focused upstream failure-path and package-consumer regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../WinUIMtpPackagedApp/Probe-Extensions.ps1 | 13 +- samples/public/WinUIMtpPackagedApp/README.md | 2 +- .../PackagedAppControllerArguments.cs | 2 + ...PackagedAppTestHostLauncher.ConnectBack.cs | 3 + ...PackagedAppTestHostLauncher.LooseLayout.cs | 1 + .../InternalAPI/InternalAPI.Unshipped.txt | 4 + .../PACKAGE.md | 6 + .../RetryArtifactProcessor.cs | 65 +++ ...chestrator.OrchestrateTestHostExecution.cs | 4 + .../RetryOrchestrator.OrchestrationSupport.cs | 65 ++- .../RetrySummaryReporter.cs | 56 ++- .../RetryTestHostRunner.cs | 38 ++ ...rosoft.Testing.Extensions.TrxReport.csproj | 1 + .../TrxProcessLifetimeHandler.cs | 4 + .../InternalAPI/InternalAPI.Unshipped.txt | 6 + .../DotnetTest/DotnetTestConnection.cs | 15 + .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 63 ++- .../ReportProcessLifetimeHandler.cs | 40 +- .../RetryArtifactManifest.cs | 47 ++ .../PackagedAppNativeDotnetTestTests.cs | 22 +- .../PackagedWinUITests.cs | 10 +- .../RetryFailedTestsTests.cs | 238 ++++++++++- .../PackagedAppControllerArgumentsTests.cs | 9 + .../PackagedAppTestHostLauncherTests.cs | 7 + .../RetrySummaryBehaviorTests.cs | 401 ++++++++++++++++++ .../TrxProcessLifetimeHandlerTests.cs | 50 ++- .../ServerMode/DotnetTestDataConsumerTests.cs | 166 ++++++++ 27 files changed, 1245 insertions(+), 93 deletions(-) create mode 100644 test/UnitTests/Microsoft.Testing.Extensions.UnitTests/RetrySummaryBehaviorTests.cs diff --git a/samples/public/WinUIMtpPackagedApp/Probe-Extensions.ps1 b/samples/public/WinUIMtpPackagedApp/Probe-Extensions.ps1 index 3aaa2bf44f..844282ca6e 100644 --- a/samples/public/WinUIMtpPackagedApp/Probe-Extensions.ps1 +++ b/samples/public/WinUIMtpPackagedApp/Probe-Extensions.ps1 @@ -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' diff --git a/samples/public/WinUIMtpPackagedApp/README.md b/samples/public/WinUIMtpPackagedApp/README.md index 877e37276c..8eedfa0dd5 100644 --- a/samples/public/WinUIMtpPackagedApp/README.md +++ b/samples/public/WinUIMtpPackagedApp/README.md @@ -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//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. diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppControllerArguments.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppControllerArguments.cs index c33cf85d5c..eb17392ebb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppControllerArguments.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppControllerArguments.cs @@ -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; @@ -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 "") diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.ConnectBack.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.ConnectBack.cs index 7ab4a64054..a17e5eacc0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.ConnectBack.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.ConnectBack.cs @@ -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; @@ -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) diff --git a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.LooseLayout.cs b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.LooseLayout.cs index 955d069983..249bfaf5bd 100644 --- a/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.LooseLayout.cs +++ b/src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackagedAppTestHostLauncher.LooseLayout.cs @@ -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}'."); diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt index 7dc5c58110..894bcc010b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt @@ -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! 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! finalArguments, string? currentTryResultFolder, int attemptCount, int userMaxRetryCount, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +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! replacements, System.Collections.Generic.IReadOnlyCollection! trxReportPaths, System.Func? onTrxMoved, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md b/src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md index 4aa2977f2b..147f7a6748 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/PACKAGE.md @@ -25,6 +25,12 @@ Configure retry using `--retry-failed-tests `, 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///`, 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 . diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryArtifactProcessor.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryArtifactProcessor.cs index 701039f7b9..41ff992664 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryArtifactProcessor.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryArtifactProcessor.cs @@ -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 movedArtifacts) + { + IPushOnlyProtocol? protocol = serviceProvider.GetServiceInternal(); + 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 SnapshotAttemptArtifacts( IFileSystem fileSystem, IReadOnlyList artifacts, diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrateTestHostExecution.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrateTestHostExecution.cs index b031a2536f..f2b63e57cf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrateTestHostExecution.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrateTestHostExecution.cs @@ -234,6 +234,10 @@ public async Task OrchestrateTestHostExecutionAsync(CancellationToken cance bool willRetry = attemptCount < userMaxRetryCount + 1; if (willRetry) { + await RetryArtifactProcessor.PublishDeferredTrxArtifactsAsync( + _serviceProvider, + retryRootFolder, + new Dictionary()).ConfigureAwait(false); await outputDevice.DisplayAsync( this, new FormattedTextOutputDeviceData(string.Format(CultureInfo.CurrentCulture, ExtensionResources.RetryAttemptFailedWillRetry, attemptCount, userMaxRetryCount + 1, failedThisAttempt)) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrationSupport.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrationSupport.cs index d040cd4ba2..59bf30fe55 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrationSupport.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.OrchestrationSupport.cs @@ -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; @@ -133,6 +135,7 @@ await LogResponseFileFallbackWarningAsync( retryFailedTestsPipeServer, executableInfo, finalArguments, + currentTryResultFolder, attemptCount, userMaxRetryCount, cancellationToken).ConfigureAwait(false); @@ -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 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 { diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetrySummaryReporter.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetrySummaryReporter.cs index 4f0cd39756..90a18692ad 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetrySummaryReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetrySummaryReporter.cs @@ -234,6 +234,27 @@ public static Task MoveArtifactsAsync( new Dictionary(), cancellationToken); + public static Task MoveArtifactsAsync( + IOutputDeviceDataProducer producer, + IOutputDevice outputDevice, + IFileSystem fileSystem, + ILogger logger, + string currentTryResultFolder, + string resultDirectory, + IReadOnlyDictionary replacements, + CancellationToken cancellationToken) + => MoveArtifactsAsync( + producer, + outputDevice, + fileSystem, + logger, + currentTryResultFolder, + resultDirectory, + replacements, + trxReportPaths: [], + onTrxMoved: null, + cancellationToken); + public static async Task MoveArtifactsAsync( IOutputDeviceDataProducer producer, IOutputDevice outputDevice, @@ -242,6 +263,8 @@ public static async Task MoveArtifactsAsync( string currentTryResultFolder, string resultDirectory, IReadOnlyDictionary replacements, + IReadOnlyCollection trxReportPaths, + Func? onTrxMoved, CancellationToken cancellationToken) { string[] filesToMove = fileSystem.GetFiles(currentTryResultFolder, "*.*", SearchOption.AllDirectories); @@ -250,8 +273,12 @@ public static async Task MoveArtifactsAsync( return; } - // Preserve the final attempt under Retries like every earlier attempt, and publish copies at the top level. - // A retry-aware post-processor can replace a final-attempt report with one describing the logical run. + HashSet reportedTrxPaths = new( + trxReportPaths.Select(Path.GetFullPath), + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + + // Post-processed reports retain their inputs; raw TRX reports must have only one publishable copy. + List<(string Source, string Destination)> copiedTrxFiles = []; foreach (string file in filesToMove) { string relativePath = file.Substring(currentTryResultFolder.Length) @@ -260,7 +287,20 @@ public static async Task MoveArtifactsAsync( resultDirectory, relativePath); string normalizedFile = Path.GetFullPath(file); - string sourceFile = replacements.TryGetValue(normalizedFile, out string? replacement) ? replacement : file; + string sourceFile; + if (replacements.TryGetValue(normalizedFile, out string? replacement)) + { + sourceFile = replacement; + } + else + { + sourceFile = file; + if (reportedTrxPaths.Contains(normalizedFile) + && Path.GetExtension(file).Equals(".trx", StringComparison.OrdinalIgnoreCase)) + { + copiedTrxFiles.Add((file, finalFileLocation)); + } + } // Create the directory if missing fileSystem.CreateDirectory(Path.GetDirectoryName(finalFileLocation)!); @@ -270,6 +310,16 @@ public static async Task MoveArtifactsAsync( fileSystem.CopyFile(sourceFile, finalFileLocation, overwrite: true); } + // Keep the original reports if copying any artifact fails. + foreach ((string source, string destination) in copiedTrxFiles) + { + fileSystem.DeleteFile(source); + if (onTrxMoved is not null) + { + await onTrxMoved(source, destination).ConfigureAwait(false); + } + } + Task displayTask = outputDevice.DisplayAsync( producer, new FormattedTextOutputDeviceData(string.Format(CultureInfo.CurrentCulture, ExtensionResources.RetryArtifactsPublished, filesToMove.Length, resultDirectory)) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryTestHostRunner.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryTestHostRunner.cs index f1bc6c5da9..b005845041 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryTestHostRunner.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryTestHostRunner.cs @@ -6,8 +6,10 @@ using Microsoft.Testing.Platform.Extensions.OutputDevice; using Microsoft.Testing.Platform.Extensions.TestHostControllers; using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.IPC; 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; @@ -36,6 +38,30 @@ public readonly struct AttemptResult #pragma warning restore RS0051 } + public static Task RunAttemptAsync( + IServiceProvider serviceProvider, + IOutputDeviceDataProducer producer, + IOutputDevice outputDevice, + ILogger logger, + RetryFailedTestsPipeServer retryFailedTestsPipeServer, + ExecutableInfo executableInfo, + List finalArguments, + int attemptCount, + int userMaxRetryCount, + CancellationToken cancellationToken) + => RunAttemptAsync( + serviceProvider, + producer, + outputDevice, + logger, + retryFailedTestsPipeServer, + executableInfo, + finalArguments, + currentTryResultFolder: null, + attemptCount, + userMaxRetryCount, + cancellationToken); + public static async Task RunAttemptAsync( IServiceProvider serviceProvider, IOutputDeviceDataProducer producer, @@ -44,6 +70,7 @@ public static async Task RunAttemptAsync( RetryFailedTestsPipeServer retryFailedTestsPipeServer, ExecutableInfo executableInfo, List finalArguments, + string? currentTryResultFolder, int attemptCount, int userMaxRetryCount, CancellationToken cancellationToken) @@ -70,6 +97,17 @@ public static async Task RunAttemptAsync( { UseShellExecute = false, }; + processStartInfo.EnvironmentVariables.Remove(DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable); + processStartInfo.EnvironmentVariables.Remove(DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable); + if (currentTryResultFolder is not null + && (serviceProvider.GetServiceInternal() is { IsServerMode: true } + || serviceProvider.GetEnvironment().GetEnvironmentVariable(DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable) is { Length: > 0 })) + { + processStartInfo.EnvironmentVariables[DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable] = currentTryResultFolder; + processStartInfo.EnvironmentVariables[DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable] = + RetryArtifactProcessor.GetDeferredTrxArtifactDirectory(Path.GetDirectoryName(currentTryResultFolder)!); + } + string recoveredArtifactManifestPath = Path.Combine( Path.GetTempPath(), $"testfx-retry-recovered-artifacts-{Guid.NewGuid():N}.txt"); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj b/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj index 1829f22f2a..0cead0d564 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj @@ -37,6 +37,7 @@ + diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs index 519882d123..db07e9e0cc 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs @@ -252,6 +252,8 @@ await _messageBus.PublishAsync( ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription, TrxReportEngine.TrxArtifactKind)).ConfigureAwait(false); + await RetryArtifactManifest.WriteArtifactAsync( + _environment, _fileSystem, _logger, fileName, TrxReportEngine.TrxArtifactKind, cancellationToken).ConfigureAwait(false); TryDeleteStreamingSidecar(); return; @@ -289,6 +291,8 @@ await _messageBus.PublishAsync( } await _messageBus.PublishAsync(this, new FileArtifact(trxFile, ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription, TrxReportEngine.TrxArtifactKind)).ConfigureAwait(false); + await RetryArtifactManifest.WriteArtifactAsync( + _environment, _fileSystem, _logger, trxFile.FullName, TrxReportEngine.TrxArtifactKind, cancellationToken).ConfigureAwait(false); // Best-effort orphan cleanup. On the happy path the test host normally deletes its own // sidecar in TrxReportGenerator.GenerateReportAndCleanupAsync, but if its CompleteAsync timed diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 56e03defd8..a10894bcd5 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -1,4 +1,10 @@ #nullable enable +const Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable = "TESTINGPLATFORM_DOTNETTEST_ARTIFACT_REPLAY_PIPE" -> string! +static Microsoft.Testing.Platform.DotnetTestConnection.SendFileArtifactsToPipeAsync(string! pipeName, Microsoft.Testing.Platform.IPC.Models.FileArtifactMessages! message, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +const Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable = "TESTINGPLATFORM_RETRY_DEFERRED_TRX_DIRECTORY" -> string! +const Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable = "TESTINGPLATFORM_RETRY_DEFERRED_TRX_ROOT" -> string! +static Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.TryDeferTrxArtifacts(Microsoft.Testing.Platform.IPC.Models.FileArtifactMessages! message, string? attemptRoot, string? publicationDirectory) -> bool +static Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.ReadDeferredTrxArtifacts(string! manifestPath) -> Microsoft.Testing.Platform.IPC.Models.FileArtifactMessages! Microsoft.Testing.Platform.OutputDevice.GitHubActionsCommandOutputDeviceData Microsoft.Testing.Platform.OutputDevice.GitHubActionsCommandOutputDeviceData.GitHubActionsCommandOutputDeviceData(string! text) -> void Microsoft.Testing.Platform.OutputDevice.TerminalOutputDevice.TestSessionFailureProvider.get -> System.Func! diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 75c560f536..cf84237da1 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -58,6 +58,21 @@ public DotnetTestConnection(CommandLineHandler commandLineHandler, IEnvironment public Task GetDataConsumerAsync() => Task.FromResult((IPushOnlyProtocolConsumer)new DotnetTestDataConsumer(this, _environment)); + [UnsupportedOSPlatform("browser")] + [UnsupportedOSPlatform("wasi")] + internal static async Task SendFileArtifactsToPipeAsync( + string pipeName, + FileArtifactMessages message, + IEnvironment environment, + CancellationToken cancellationToken) + { + // The activated host owns the SDK handshake; replay its envelopes without announcing the controller's runtime. + using var client = new NamedPipeClient(pipeName, environment); + client.RegisterAllSerializers(); + await client.ConnectAsync(cancellationToken).ConfigureAwait(false); + await client.RequestReplyAsync(message, cancellationToken).ConfigureAwait(false); + } + public async Task AfterCommonServiceSetupAsync() { if (_commandLineHandler.HasDotnetTestServerOption() diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index dd626a8553..cc55c8b139 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -4,6 +4,7 @@ using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.IPC.Models; +using Microsoft.Testing.Platform.IPC.Serializers; using Microsoft.Testing.Platform.OutputDevice.Terminal; using Microsoft.Testing.Platform.ServerMode; using Microsoft.Testing.Platform.Services; @@ -12,13 +13,21 @@ namespace Microsoft.Testing.Platform.IPC; internal sealed class DotnetTestDataConsumer : IPushOnlyProtocolConsumer { + internal const string DeferredTrxRootEnvironmentVariable = "TESTINGPLATFORM_RETRY_DEFERRED_TRX_ROOT"; + internal const string DeferredTrxDirectoryEnvironmentVariable = "TESTINGPLATFORM_RETRY_DEFERRED_TRX_DIRECTORY"; + internal const string ArtifactReplayPipeEnvironmentVariable = "TESTINGPLATFORM_DOTNETTEST_ARTIFACT_REPLAY_PIPE"; + private readonly DotnetTestConnection? _dotnetTestConnection; private readonly string? _executionId; + private readonly string? _deferredTrxRoot; + private readonly string? _deferredTrxDirectory; public DotnetTestDataConsumer(DotnetTestConnection dotnetTestConnection, IEnvironment environment) { _dotnetTestConnection = dotnetTestConnection; _executionId = environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID); + _deferredTrxRoot = environment.GetEnvironmentVariable(DeferredTrxRootEnvironmentVariable); + _deferredTrxDirectory = environment.GetEnvironmentVariable(DeferredTrxDirectoryEnvironmentVariable); } public Type[] DataTypesConsumed => @@ -172,7 +181,10 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella null) ]); - await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages).ConfigureAwait(false); + if (!TryDeferTrxArtifacts(testFileArtifactMessages, _deferredTrxRoot, _deferredTrxDirectory)) + { + await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages).ConfigureAwait(false); + } } break; @@ -180,17 +192,62 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella case SessionFileArtifact sessionFileArtifact: FileArtifactMessages fileArtifactMessages = CreateFileArtifactMessages(_executionId, sessionFileArtifact); - await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); + if (!TryDeferTrxArtifacts(fileArtifactMessages, _deferredTrxRoot, _deferredTrxDirectory)) + { + await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); + } + break; case FileArtifact fileArtifact: fileArtifactMessages = CreateFileArtifactMessages(_executionId, fileArtifact); - await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); + if (!TryDeferTrxArtifacts(fileArtifactMessages, _deferredTrxRoot, _deferredTrxDirectory)) + { + await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); + } + break; } } + internal static bool TryDeferTrxArtifacts(FileArtifactMessages message, string? attemptRoot, string? publicationDirectory) + { + if (attemptRoot is null + || message.FileArtifacts is not [{ FullPath: { } path }] + || !Path.GetExtension(path).Equals(".trx", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string prefix = Path.GetFullPath(attemptRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + StringComparison comparison = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; + if (!Path.GetFullPath(path).StartsWith(prefix, comparison)) + { + return false; + } + + ApplicationStateGuard.Ensure(publicationDirectory is not null); + Directory.CreateDirectory(publicationDirectory); + string temporaryPath = Path.Combine(publicationDirectory, $"{Guid.NewGuid():N}.tmp"); + using (var stream = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + new FileArtifactMessagesSerializer().Serialize(message, stream); + } + + File.Move(temporaryPath, Path.ChangeExtension(temporaryPath, ".bin")); + return true; + } + + internal static FileArtifactMessages ReadDeferredTrxArtifacts(string manifestPath) + { + using var stream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read, FileShare.Read); + return new FileArtifactMessagesSerializer().Deserialize(stream); + } + // Maps a session-scoped artifact to its wire message. Extracted so the producer-to-wire mapping // (in particular the Kind carried for post-processing grouping) is unit-testable without a live pipe. internal static FileArtifactMessages CreateFileArtifactMessages(string? executionId, SessionFileArtifact sessionFileArtifact) diff --git a/src/Platform/SharedExtensionHelpers/ReportProcessLifetimeHandler.cs b/src/Platform/SharedExtensionHelpers/ReportProcessLifetimeHandler.cs index c39693eb84..fecd2d79a1 100644 --- a/src/Platform/SharedExtensionHelpers/ReportProcessLifetimeHandler.cs +++ b/src/Platform/SharedExtensionHelpers/ReportProcessLifetimeHandler.cs @@ -163,46 +163,12 @@ await _outputDevice.DisplayAsync( } } - private async Task WriteRetryArtifactManifestAsync( + private Task WriteRetryArtifactManifestAsync( string artifactPath, string? artifactKind, CancellationToken cancellationToken) - { - const string retryArtifactManifestEnvironmentVariable = "TESTINGPLATFORM_RETRY_RECOVERED_ARTIFACT_MANIFEST"; - string? manifestPath = _environment.GetEnvironmentVariable(retryArtifactManifestEnvironmentVariable); - if (manifestPath is null || manifestPath.Length == 0) - { - return; - } - - try - { - string? directory = Path.GetDirectoryName(manifestPath); - if (directory is not null && directory.Length > 0) - { - _fileSystem.CreateDirectory(directory); - } - - string entry = RetryArtifactManifest.WriteEntry(artifactPath, artifactKind); - using IFileStream stream = _fileSystem.NewFileStream( - manifestPath, - FileMode.Append, - FileAccess.Write, - FileShare.Read); - using var writer = new StreamWriter(stream.Stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); -#if NETCOREAPP - await writer.WriteLineAsync(entry.AsMemory(), cancellationToken).ConfigureAwait(false); -#else - cancellationToken.ThrowIfCancellationRequested(); - await writer.WriteLineAsync(entry).ConfigureAwait(false); -#endif - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - await _logger.LogWarningAsync( - $"Failed to register recovered report '{artifactPath}' with retry artifact consolidation: {ex.Message}").ConfigureAwait(false); - } - } + => RetryArtifactManifest.WriteArtifactAsync( + _environment, _fileSystem, _logger, artifactPath, artifactKind, cancellationToken); private void TryDeleteJournal(string path) { diff --git a/src/Platform/SharedExtensionHelpers/RetryArtifactManifest.cs b/src/Platform/SharedExtensionHelpers/RetryArtifactManifest.cs index 98ca45af29..8bc3060b97 100644 --- a/src/Platform/SharedExtensionHelpers/RetryArtifactManifest.cs +++ b/src/Platform/SharedExtensionHelpers/RetryArtifactManifest.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Logging; + namespace Microsoft.Testing.Extensions; #pragma warning disable RS0051 // Recovery infrastructure is shared-source implementation detail, not package API. @@ -44,6 +47,50 @@ public static string WriteEntry(string path, string? kind) => WriteEntryWithEncodedKind( path, kind is null ? "-" : Convert.ToBase64String(Encoding.UTF8.GetBytes(kind))); + + public static async Task WriteArtifactAsync( + IEnvironment environment, + IFileSystem fileSystem, + ILogger logger, + string artifactPath, + string? artifactKind, + CancellationToken cancellationToken) + { + const string retryArtifactManifestEnvironmentVariable = "TESTINGPLATFORM_RETRY_RECOVERED_ARTIFACT_MANIFEST"; + string? manifestPath = environment.GetEnvironmentVariable(retryArtifactManifestEnvironmentVariable); + if (manifestPath is null || manifestPath.Length == 0) + { + return; + } + + try + { + string? directory = Path.GetDirectoryName(manifestPath); + if (directory is not null && directory.Length > 0) + { + fileSystem.CreateDirectory(directory); + } + + string entry = WriteEntry(artifactPath, artifactKind); + using IFileStream stream = fileSystem.NewFileStream( + manifestPath, + FileMode.Append, + FileAccess.Write, + FileShare.Read); + using var writer = new StreamWriter(stream.Stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); +#if NETCOREAPP + await writer.WriteLineAsync(entry.AsMemory(), cancellationToken).ConfigureAwait(false); +#else + cancellationToken.ThrowIfCancellationRequested(); + await writer.WriteLineAsync(entry).ConfigureAwait(false); +#endif + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + await logger.LogWarningAsync( + $"Failed to register recovered report '{artifactPath}' with retry artifact consolidation: {ex.Message}").ConfigureAwait(false); + } + } } #pragma warning restore RS0051 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PackagedAppNativeDotnetTestTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PackagedAppNativeDotnetTestTests.cs index aa8560a79d..94ba6481a8 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PackagedAppNativeDotnetTestTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PackagedAppNativeDotnetTestTests.cs @@ -103,13 +103,27 @@ await WindowsApplicationModelTestTools.ExecuteWithPackageCleanupAsync( { string[] attempts = Directory.GetFiles(Path.Combine(results, "Retries"), "native_report.trx", SearchOption.AllDirectories) .Order(StringComparer.Ordinal).ToArray(); - Assert.HasCount(2, attempts); + string firstAttemptPath = Assert.ContainsSingle(attempts); + Assert.AreEqual("1", Path.GetFileName(Path.GetDirectoryName(firstAttemptPath))); XElement[] firstAttempt = XDocument.Load(attempts[0]).Descendants(ns + "UnitTestResult").ToArray(); - XElement[] secondAttempt = XDocument.Load(attempts[1]).Descendants(ns + "UnitTestResult").ToArray(); Assert.HasCount(2, firstAttempt); Assert.HasCount(1, firstAttempt.Where(test => (string?)test.Attribute("outcome") == "Failed")); - Assert.HasCount(1, secondAttempt); - Assert.AreEqual("Passed", (string?)secondAttempt[0].Attribute("outcome")); + string retryRoot = Path.GetDirectoryName(Path.GetDirectoryName(firstAttemptPath)!)!; + Assert.IsFalse(File.Exists(Path.Combine(retryRoot, "2", "native_report.trx"))); + Assert.AreEqual("Outcome", (string?)Assert.ContainsSingle(tests).Attribute("testName")); + Assert.AreEqual("Passed", (string?)tests[0].Attribute("outcome")); + string[] reports = Directory.GetFiles(results, "*.trx", SearchOption.AllDirectories); + Assert.HasCount(2, reports); + string[] advertised = + [ + .. Regex.Matches(NormalizeConsoleOutput(result.StandardOutput), @"(?m)^\s*-\s+(?[^\r\n]+\.trx)\s*$") + .Select(match => match.Groups["path"].Value.Trim()), + ]; + Assert.AreSequenceEqual( + reports.Order(StringComparer.Ordinal), + advertised.Order(StringComparer.Ordinal), + "The native packaged SDK must advertise only the retained and final published report paths."); + Assert.IsTrue(advertised.All(File.Exists), result.StandardOutput + result.ErrorOutput); } }); } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedWinUITests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedWinUITests.cs index 4a25f7c3b8..c807151d80 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedWinUITests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/PackagedWinUITests.cs @@ -940,18 +940,18 @@ private static void AssertRetryWinUITrx(string resultsDirectory, string finalTrx string firstAttemptTrxPath = Path.Combine(attemptDirectories.Single(path => Path.GetFileName(path) == "1"), "appcontainer-retry.trx"); string secondAttemptTrxPath = Path.Combine(attemptDirectories.Single(path => Path.GetFileName(path) == "2"), "appcontainer-retry.trx"); var firstAttemptTrx = XDocument.Load(firstAttemptTrxPath); - var secondAttemptTrx = XDocument.Load(secondAttemptTrxPath); XElement[] firstAttemptResults = [.. firstAttemptTrx.Descendants(ns + "UnitTestResult")]; - XElement[] secondAttemptResults = [.. secondAttemptTrx.Descendants(ns + "UnitTestResult")]; Assert.HasCount(6, firstAttemptResults, firstAttemptTrxPath); Assert.AreEqual( "Failed", (string?)firstAttemptResults.Single(result => (string?)result.Attribute("testName") == "RetryTestMethod_PassesOnSecondAppContainerHost").Attribute("outcome"), firstAttemptTrxPath); - XElement secondAttemptResult = Assert.ContainsSingle(secondAttemptResults); - Assert.AreEqual("RetryTestMethod_PassesOnSecondAppContainerHost", (string?)secondAttemptResult.Attribute("testName"), secondAttemptTrxPath); - Assert.AreEqual("Passed", (string?)secondAttemptResult.Attribute("outcome"), secondAttemptTrxPath); + Assert.IsFalse(File.Exists(secondAttemptTrxPath), "The final attempt must not retain a duplicate TRX under Retries."); + Assert.AreEqual( + firstAttemptTrxPath, + Assert.ContainsSingle(Directory.GetFiles(retryDirectory, "*.trx", SearchOption.AllDirectories))); + Assert.HasCount(2, Directory.GetFiles(resultsDirectory, "*.trx", SearchOption.AllDirectories)); } private static void AssertResolvedWinUIAssets(string reportPath, bool usingSdk = true) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index 76ba280f42..212473590b 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -91,7 +91,7 @@ public async Task RetryFailedTests_OnlyRetryTimes_Succeeds(string tfm, bool fail testHostResult.AssertOutputDoesNotContain("Test run summary: Passed!"); string[] trxFiles = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.AllDirectories); - Assert.HasCount(3, trxFiles); + Assert.HasCount(2, trxFiles); string[] trxContents = [.. trxFiles.Select(File.ReadAllText)]; Assert.HasCount(2, trxContents.Distinct(StringComparer.Ordinal)); string[] ids = @@ -124,6 +124,183 @@ .. trxContents } } + [TestMethod] + [DataRow("--retry-failed-tests 1", true, true, 2, false, false, DisplayName = "RetryTrx_PersistentFailure")] + [DataRow("--retry-failed-tests 1", true, false, 2, true, false, DisplayName = "RetryTrx_Recovery")] + [DataRow("--retry-failed-tests 1 --retry-failed-tests-max-percentage 10", true, true, 1, false, false, DisplayName = "RetryTrx_ThresholdSuppressed")] + [DataRow("--retry-failed-tests 1", false, false, 1, true, false, DisplayName = "RetryTrx_AllPass")] + [DataRow("--retry-failed-tests 0", true, true, 1, false, false, DisplayName = "RetryTrx_ZeroRetries")] + [DataRow("--retry-failed-tests 0", true, true, 1, false, true, DisplayName = "RetryTrx_AbsoluteZeroRetries")] + [DataRow("", true, true, 1, false, false, DisplayName = "RetryTrx_Disabled")] + public async Task RetryFailedTests_TrxReports_ArePublishedOncePerAttempt( + string retryArguments, bool failOnFirstAttempt, bool alwaysFail, int expectedAttempts, bool expectSuccess, bool absoluteReportPath) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent); + string resultDirectory = Path.Combine(testHost.DirectoryName, Guid.NewGuid().ToString("N")); + string reportFileName = absoluteReportPath ? Path.Combine(resultDirectory, "retry.trx") : "retry.trx"; + TestHostResult testHostResult = await testHost.ExecuteAsync( + $"{retryArguments} --report-trx --report-trx-filename \"{reportFileName}\" --results-directory \"{resultDirectory}\"", + new() + { + [EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT] = "1", + ["METHOD1"] = failOnFirstAttempt ? "1" : null, + ["METHOD2"] = null, + ["METHOD3"] = null, + ["FAIL"] = alwaysFail ? "1" : "0", + ["CRASH"] = null, + ["CRASHONRETRY"] = null, + ["SKIPONRETRY"] = null, + ["CHECK_RETRY_RESPONSE_FILE_CLEANUP"] = null, + ["TRX_ATTACHMENTS"] = "1", + ["RESULTDIR"] = resultDirectory, + }, + cancellationToken: TestContext.CancellationToken); + + testHostResult.AssertExitCodeIs(expectSuccess ? ExitCode.Success : ExitCode.AtLeastOneTestFailed); + string[] trxFiles = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.AllDirectories); + Assert.HasCount(expectedAttempts, trxFiles, "Recursive TRX collection must include each physical attempt exactly once."); + Assert.HasCount(1, Directory.GetFiles(resultDirectory, "*.trx", SearchOption.TopDirectoryOnly)); + XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; + HashSet executionIds = []; + HashSet runIds = []; + List<(string Name, string Outcome)> observedResults = []; + foreach (string trxFile in trxFiles) + { + var report = XDocument.Load(trxFile); + runIds.Add(report.Root!.Attribute("id")!.Value); + string reportDirectory = Path.GetDirectoryName(trxFile)!; + foreach (XElement result in report.Descendants(ns + "UnitTestResult")) + { + string name = result.Attribute("testName")!.Value; + observedResults.Add((name, result.Attribute("outcome")!.Value)); + Assert.IsTrue(executionIds.Add(result.Attribute("executionId")!.Value), "The same physical result must not be published twice."); + if (name != "TestMethod1") + { + continue; + } + + string relativeResultsDirectory = result.Attribute("relativeResultsDirectory")!.Value; + string resultFile = result.Descendants(ns + "ResultFile").Single().Attribute("path")!.Value; + string deploymentRoot = report.Descendants(ns + "Deployment").Single().Attribute("runDeploymentRoot")!.Value; + string attachment = Path.Combine( + reportDirectory, deploymentRoot, "In", relativeResultsDirectory, + resultFile.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)); + string expectedAttachment = expectedAttempts > 1 && reportDirectory == resultDirectory ? "retry attachment" : "initial attachment"; + Assert.AreEqual(expectedAttachment, File.ReadAllText(attachment)); + } + } + + Assert.HasCount(1, runIds); + List<(string Name, string Outcome)> expectedResults = + [ + ("TestMethod1", failOnFirstAttempt ? "Failed" : "Passed"), + ("TestMethod2", "Passed"), + ("TestMethod3", "Passed"), + ]; + if (expectedAttempts > 1) + { + expectedResults.Add(("TestMethod1", alwaysFail ? "Failed" : "Passed")); + } + + Assert.AreSequenceEqual( + expectedResults.OrderBy(result => result.Name, StringComparer.Ordinal).ThenBy(result => result.Outcome, StringComparer.Ordinal), + observedResults.OrderBy(result => result.Name, StringComparer.Ordinal).ThenBy(result => result.Outcome, StringComparer.Ordinal)); + } + + [TestMethod] + [DataRow(false, DisplayName = "RetryTrxAttachment_CtrfOnly")] + [DataRow(true, DisplayName = "RetryTrxAttachment_CtrfAndTrx")] + public async Task RetryFailedTests_CtrfPreservesTrxNamedAttachments(bool reportTrx) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent); + string resultDirectory = Path.Combine(testHost.DirectoryName, Guid.NewGuid().ToString("N")); + string trxArguments = reportTrx ? "--report-trx --report-trx-filename report.trx" : string.Empty; + TestHostResult result = await testHost.ExecuteAsync( + $"--retry-failed-tests 1 --report-ctrf {trxArguments} --results-directory \"{resultDirectory}\"", + new() + { + ["METHOD1"] = "1", + ["METHOD2"] = null, + ["METHOD3"] = null, + ["FAIL"] = "0", + ["CRASH"] = null, + ["CRASHONRETRY"] = null, + ["SKIPONRETRY"] = null, + ["TRX_ATTACHMENTS"] = null, + ["CTRF_TRX_ATTACHMENT"] = "1", + ["RESULTDIR"] = resultDirectory, + }, + cancellationToken: TestContext.CancellationToken); + + result.AssertExitCodeIs(ExitCode.Success); + string retryRoot = Assert.ContainsSingle(Directory.GetDirectories(Path.Combine(resultDirectory, "Retries"))); + string[] reports = Directory.GetFiles(resultDirectory, "*.ctrf.json", SearchOption.AllDirectories); + Assert.HasCount(3, reports); + foreach (string reportPath in reports) + { + using var report = System.Text.Json.JsonDocument.Parse(File.ReadAllText(reportPath)); + System.Text.Json.JsonElement test = report.RootElement.GetProperty("results").GetProperty("tests") + .EnumerateArray().Single(test => test.GetProperty("name").GetString() == "TestMethod1"); + string attempt = Path.GetDirectoryName(reportPath) == resultDirectory ? "2" : Path.GetFileName(Path.GetDirectoryName(reportPath))!; + Assert.AreEqual(attempt == "1" ? "failed" : "passed", test.GetProperty("status").GetString()); + System.Text.Json.JsonElement attachment = Assert.ContainsSingle(test.GetProperty("attachments").EnumerateArray()); + string path = attachment.GetProperty("path").GetString()!; + Assert.AreEqual(Path.Combine(retryRoot, attempt, "diagnostics.trx"), path); + Assert.IsTrue(File.Exists(path), "Every retained and consolidated CTRF attachment must still exist at its recorded path."); + Assert.AreEqual(attempt == "1" ? "initial diagnostics" : "retry diagnostics", File.ReadAllText(path)); + } + + string[] trxReports = Directory.GetFiles(resultDirectory, "report.trx", SearchOption.AllDirectories); + Assert.HasCount(reportTrx ? 2 : 0, trxReports); + if (reportTrx) + { + Assert.IsTrue(File.Exists(Path.Combine(resultDirectory, "report.trx"))); + Assert.IsTrue(File.Exists(Path.Combine(retryRoot, "1", "report.trx"))); + Assert.IsFalse(File.Exists(Path.Combine(retryRoot, "2", "report.trx"))); + } + } + + [TestMethod] + [DataRow(true, DisplayName = "RetryTrx_NativePersistentFailure")] + [DataRow(false, DisplayName = "RetryTrx_NativeRecovery")] + public async Task RetryFailedTests_NativeSdkPublishesExistingTrxPaths(bool alwaysFail) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent); + string resultDirectory = Path.Combine(testHost.DirectoryName, Guid.NewGuid().ToString("N")); + // Check retry publication without the SDK adding a separate merged-module report. + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"test --test-modules {AssetName}.dll --root-directory \"{testHost.DirectoryName}\" --results-directory \"{resultDirectory}\" --report-trx --retry-failed-tests 1 --no-artifact-post-processing --no-ansi --no-progress", + workingDirectory: Constants.Root, + environmentVariables: new() + { + ["METHOD1"] = "1", + ["METHOD2"] = null, + ["METHOD3"] = null, + ["FAIL"] = alwaysFail ? "1" : "0", + ["CRASH"] = null, + ["CRASHONRETRY"] = null, + ["SKIPONRETRY"] = null, + ["RESULTDIR"] = resultDirectory, + }, + failIfReturnValueIsNotZero: false, + warnAsError: false, + cancellationToken: TestContext.CancellationToken); + + result.AssertExitCodeIs(alwaysFail ? ExitCode.AtLeastOneTestFailed : ExitCode.Success); + string[] reports = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.AllDirectories); + Assert.HasCount(2, reports, "Native SDK collection must include one TRX for each physical attempt."); + string[] advertised = + [ + .. Regex.Matches(result.StandardOutput, @"(?m)^\s*-\s+(?[^\r\n]+\.trx)\s*$") + .Select(match => match.Groups["path"].Value.Trim()), + ]; + Assert.AreSequenceEqual( + reports.OrderBy(path => path, StringComparer.Ordinal), + advertised.OrderBy(path => path, StringComparer.Ordinal), + "The SDK must advertise the final published paths, not deleted per-attempt copies."); + Assert.IsTrue(advertised.All(File.Exists), result.ToString()); + } + [TestMethod] [DynamicData(nameof(GetResponseFileMatrix))] public async Task RetryFailedTests_WithArgumentsInResponseFile_Succeeds(bool retryArgumentsInResponseFile, bool useInlineDelimiters, string tfm) @@ -621,7 +798,7 @@ public async Task RetryFailedTests_WithPreexistingTreeNodeFilter_ReplacesFilterO // Verify that the first attempt honored the treenode-filter. string[] retryTrxFiles = Directory.GetFiles(Path.Combine(resultDirectory, "Retries"), "*.trx", SearchOption.AllDirectories); - Assert.HasCount(2, retryTrxFiles); + Assert.HasCount(1, retryTrxFiles); string firstAttemptTrxContent = File.ReadAllText( retryTrxFiles.Single(file => Path.GetFileName(Path.GetDirectoryName(file)) == "1")); @@ -629,20 +806,14 @@ public async Task RetryFailedTests_WithPreexistingTreeNodeFilter_ReplacesFilterO Assert.Contains("TestMethod2", firstAttemptTrxContent); Assert.DoesNotContain("TestMethod3", firstAttemptTrxContent); - // Verify that the retry attempt only ran the failed test (TestMethod1) - i.e. the treenode-filter was - // dropped and replaced by --filter-uid 1. - string finalAttemptTrxContent = File.ReadAllText( - retryTrxFiles.Single(file => Path.GetFileName(Path.GetDirectoryName(file)) == "2")); - Assert.Contains("TestMethod1", finalAttemptTrxContent); - Assert.DoesNotContain("TestMethod2", finalAttemptTrxContent); - Assert.DoesNotContain("TestMethod3", finalAttemptTrxContent); - - // TRX intentionally keeps final-attempt semantics, so the top-level file is a copy of attempt 2. + // The final attempt is moved to the top level and contains only the failed test selected for retry. string[] topLevelTrxFiles = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.TopDirectoryOnly); Assert.HasCount(1, topLevelTrxFiles); string trxContent = File.ReadAllText(topLevelTrxFiles[0]); - Assert.AreEqual(finalAttemptTrxContent, trxContent); + Assert.Contains("TestMethod1", trxContent); + Assert.DoesNotContain("TestMethod2", trxContent); + Assert.DoesNotContain("TestMethod3", trxContent); } [TestMethod] @@ -1033,6 +1204,7 @@ public override (string ID, string Name, string Code) GetAssetsToGenerate() => ( using Microsoft.Testing.Extensions.TrxReport.Abstractions; using Microsoft.Testing.Platform.Builder; using Microsoft.Testing.Platform.Capabilities.TestFramework; +using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Extensions; using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.TestFramework; @@ -1049,7 +1221,7 @@ public static async Task Main(string[] args) TreeNodeFilterExtension treeNodeFilterExtension = new(); builder.RegisterTestFramework( sp => new TestFrameworkCapabilities(new TrxReportCapability()), - (_,__) => new DummyTestFramework()); + (_,sp) => new DummyTestFramework((ICommandLineOptions)sp.GetService(typeof(ICommandLineOptions))!)); builder.AddCrashDumpProvider(); builder.AddTrxReportProvider(); #pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. @@ -1085,6 +1257,13 @@ void ITrxReportCapability.Enable() public class DummyTestFramework : ITestFramework, IDataProducer { + private readonly ICommandLineOptions _commandLineOptions; + + public DummyTestFramework(ICommandLineOptions commandLineOptions) + { + _commandLineOptions = commandLineOptions; + } + public string Uid => nameof(DummyTestFramework); public string Version => "2.0.0"; @@ -1140,21 +1319,42 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) Environment.FailFast("CRASHONRETRY"); } + PropertyBag properties; if (skipOnRetry) { - await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, - new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = new(new SkippedTestNodeStateProperty(), testMethod1Identifier) })); + properties = new(new SkippedTestNodeStateProperty(), testMethod1Identifier); } else if (TestMethod1(fail, resultDir, crash)) { - await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, - new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = new(PassedTestNodeStateProperty.CachedInstance, testMethod1Identifier) })); + properties = new(PassedTestNodeStateProperty.CachedInstance, testMethod1Identifier); } else { - await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, - new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = new(new FailedTestNodeStateProperty(), testMethod1Identifier) })); + properties = new(new FailedTestNodeStateProperty(), testMethod1Identifier); } + + if (Environment.GetEnvironmentVariable("TRX_ATTACHMENTS") == "1") + { + string attachmentPath = Path.Combine(resultDir, uidFilter is null ? "initial-attachment.txt" : "retry-attachment.txt"); + File.WriteAllText(attachmentPath, uidFilter is null ? "initial attachment" : "retry attachment"); + properties.Add(new FileArtifactProperty(new FileInfo(attachmentPath), "Retry attachment", "Per-attempt attachment")); + } + + if (Environment.GetEnvironmentVariable("CTRF_TRX_ATTACHMENT") == "1") + { + if (!_commandLineOptions.TryGetOptionArgumentList("results-directory", out string[]? resultDirectories)) + { + throw new InvalidOperationException("The attachment fixture requires a results directory."); + } + + Directory.CreateDirectory(resultDirectories[0]); + string attachmentPath = Path.Combine(resultDirectories[0], "diagnostics.trx"); + File.WriteAllText(attachmentPath, uidFilter is null ? "initial diagnostics" : "retry diagnostics"); + properties.Add(new FileArtifactProperty(new FileInfo(attachmentPath), "TRX-named diagnostics")); + } + + await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, + new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = properties })); } if (IsIncluded(uidFilter, treeNodeFilter, "2", "TestMethod2")) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppControllerArgumentsTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppControllerArgumentsTests.cs index 3322bd8196..2f941e8e08 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppControllerArgumentsTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppControllerArgumentsTests.cs @@ -4,6 +4,7 @@ #if !NETFRAMEWORK using Microsoft.Testing.Extensions.PackagedApp; +using Microsoft.Testing.Platform.IPC; namespace Microsoft.Testing.Extensions.UnitTests; @@ -27,6 +28,7 @@ public void Configure_PreservesUserArgumentsAndLaunchProfileTail() Assert.AreEqual(Target, environment[PackagedAppControllerArguments.TargetEnvironmentVariable]); Assert.AreEqual("msbuild;packagedapp;trx", environment[PackagedAppControllerArguments.ExtensionsEnvironmentVariable]); Assert.AreEqual("sdk-pipe", environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable]); + Assert.AreEqual("sdk-pipe", environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); Assert.IsTrue(Guid.TryParseExact(environment[PackagedAppControllerArguments.ExecutionIdEnvironmentVariable], "N", out _)); } @@ -45,6 +47,7 @@ public void Configure_RetryKeepsTransportAndExecutionIdentity() Assert.AreSame(result, retry); Assert.AreEqual("supplied-execution-id", environment[PackagedAppControllerArguments.ExecutionIdEnvironmentVariable]); + Assert.AreEqual("sdk-pipe", environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); Assert.AreSequenceEqual( ["--retry-failed-tests", "2", "--server", "dotnettestcli", "--dotnet-test-pipe", "sdk-pipe"], PackagedAppControllerArguments.AddNativeTransport(retry, environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable])); @@ -56,6 +59,7 @@ public void Configure_DotnetRunClearsStaleTransportAndKeepsTail() Dictionary environment = new() { [PackagedAppControllerArguments.NativePipeEnvironmentVariable] = "stale-pipe", + [DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable] = "stale-replay-pipe", }; string[] result = Configure( [PackagedAppControllerArguments.Prefix, Target, "packagedapp", "--report-trx", "--results-directory", "a b"], @@ -63,6 +67,7 @@ public void Configure_DotnetRunClearsStaleTransportAndKeepsTail() Assert.AreSequenceEqual(["--report-trx", "--results-directory", "a b"], result); Assert.IsNull(environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable]); + Assert.IsNull(environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); Assert.AreSame(result, PackagedAppControllerArguments.AddNativeTransport(result, null)); } @@ -127,6 +132,7 @@ public void Configure_TestExplorerPreservesServerArgumentsWithoutNativeTransport Dictionary environment = new() { [PackagedAppControllerArguments.NativePipeEnvironmentVariable] = "stale-sdk-pipe", + [DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable] = "stale-replay-pipe", }; string[] bootstrap = [PackagedAppControllerArguments.Prefix, Target, "msbuild;packagedapp;mstest"]; (string[] arguments, bool informational) = PackagedAppControllerArguments.Configure( @@ -140,6 +146,7 @@ public void Configure_TestExplorerPreservesServerArgumentsWithoutNativeTransport Assert.AreEqual(Target, environment[PackagedAppControllerArguments.TargetEnvironmentVariable]); Assert.AreEqual("msbuild;packagedapp;mstest", environment[PackagedAppControllerArguments.ExtensionsEnvironmentVariable]); Assert.IsNull(environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable]); + Assert.IsNull(environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); Assert.IsFalse(environment.ContainsKey(PackagedAppControllerArguments.ExecutionIdEnvironmentVariable)); } @@ -187,6 +194,7 @@ public void Configure_BootstrapFilePreservesArgumentTailAndRestartTransport() Assert.AreSequenceEqual(["--retry-failed-tests", "2"], arguments); Assert.AreEqual(Target, environment[PackagedAppControllerArguments.TargetEnvironmentVariable]); Assert.AreEqual("pipe", environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable]); + Assert.AreEqual("pipe", environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); (arguments, informational) = PackagedAppControllerArguments.Configure( ["--internal-retry-pipename", "retry", "--results-directory", "a b"], name => environment.GetValueOrDefault(name), @@ -195,6 +203,7 @@ public void Configure_BootstrapFilePreservesArgumentTailAndRestartTransport() Assert.AreSequenceEqual(["--internal-retry-pipename", "retry", "--results-directory", "a b"], arguments); Assert.IsFalse(informational); Assert.AreEqual("pipe", environment[PackagedAppControllerArguments.NativePipeEnvironmentVariable]); + Assert.AreEqual("pipe", environment[DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable]); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs index 7ba3923b93..730ec26cd8 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/PackagedAppTestHostLauncherTests.cs @@ -6,6 +6,7 @@ using Microsoft.Testing.Extensions.PackagedApp; using Microsoft.Testing.Platform.Extensions.TestHostControllers; +using Microsoft.Testing.Platform.IPC; namespace Microsoft.Testing.Extensions.UnitTests; @@ -1052,6 +1053,9 @@ public void GetConnectBackEnvironment_IncludesReporterRecoveryTransport() ["TESTINGPLATFORM_HTMLREPORT_JOURNAL"] = "html.jsonl", ["TESTINGPLATFORM_JUNITREPORT_JOURNAL"] = "junit.jsonl", ["TESTINGPLATFORM_RETRY_RECOVERED_ARTIFACT_MANIFEST"] = "retry.txt", + [DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable] = "attempt-root", + [DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable] = "artifact-metadata", + [DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable] = "controller-owned-pipe", ["MSTEST_APPMODEL_CONTROLLER_EXTENSIONS"] = "msbuild;packagedapp;retry", ["TESTINGPLATFORM_SECRET"] = "must-not-flow", }, @@ -1065,7 +1069,10 @@ public void GetConnectBackEnvironment_IncludesReporterRecoveryTransport() Assert.AreEqual("html.jsonl", environment["TESTINGPLATFORM_HTMLREPORT_JOURNAL"]); Assert.AreEqual("junit.jsonl", environment["TESTINGPLATFORM_JUNITREPORT_JOURNAL"]); Assert.AreEqual("retry.txt", environment["TESTINGPLATFORM_RETRY_RECOVERED_ARTIFACT_MANIFEST"]); + Assert.AreEqual("attempt-root", environment[DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable]); + Assert.AreEqual("artifact-metadata", environment[DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable]); Assert.AreEqual("msbuild;packagedapp;retry", environment["MSTEST_APPMODEL_CONTROLLER_EXTENSIONS"]); + Assert.IsFalse(environment.ContainsKey(DotnetTestDataConsumer.ArtifactReplayPipeEnvironmentVariable)); Assert.IsFalse(environment.ContainsKey("TESTINGPLATFORM_SECRET")); } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/RetrySummaryBehaviorTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/RetrySummaryBehaviorTests.cs new file mode 100644 index 0000000000..1ec974e522 --- /dev/null +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/RetrySummaryBehaviorTests.cs @@ -0,0 +1,401 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Extensions.Policy; +using Microsoft.Testing.Extensions.UnitTests.Helpers; +using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Extensions.OutputDevice; +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; + +using Moq; + +namespace Microsoft.Testing.Extensions.UnitTests; + +[TestClass] +public sealed class RetrySummaryBehaviorTests +{ + [TestMethod] + public async Task Artifacts_EmptyTreeDoesNotPublish() + { + using var fixture = new TrxBehaviorFixture(); + fixture.FileSystem.Setup(value => value.GetFiles("attempt", "*.*", SearchOption.AllDirectories)).Returns([]); + + await RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + "attempt", "published", CancellationToken.None); + + fixture.FileSystem.Verify(value => value.GetFiles("attempt", "*.*", SearchOption.AllDirectories), Times.Once); + fixture.FileSystem.VerifyNoOtherCalls(); + Assert.IsEmpty(fixture.Displays); + Assert.IsEmpty(fixture.Logs); + } + + [TestMethod] + public async Task Artifacts_FinalTreeIsCopiedBeforePublicationWithoutRemovingAttempts() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string nested = Path.Combine(attempt, "nested", "report.trx"); + string attachment = Path.Combine(attempt, "artifacts", "trace.log"); + string merged = Path.Combine(fixture.Root, "merge", "logical.trx"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([nested, attachment]); + List operations = []; + fixture.FileSystem.Setup(value => value.CreateDirectory(It.IsAny())) + .Returns(path => + { + operations.Add("mkdir:" + path); + return path; + }); + fixture.FileSystem.Setup(value => value.CopyFile(It.IsAny(), It.IsAny(), true)) + .Callback((source, destination, _) => operations.Add("copy:" + source + "=>" + destination)); + fixture.Output.Setup(value => value.DisplayAsync( + It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((_, _, _) => operations.Add("published")) + .Returns(Task.CompletedTask); + var replacements = new Dictionary { [nested] = merged }; + + await RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, replacements, CancellationToken.None); + + Assert.AreSequenceEqual( + [ + "mkdir:" + Path.Combine(fixture.Root, "nested"), + "copy:" + merged + "=>" + Path.Combine(fixture.Root, "nested", "report.trx"), + "mkdir:" + Path.Combine(fixture.Root, "artifacts"), + "copy:" + attachment + "=>" + Path.Combine(fixture.Root, "artifacts", "trace.log"), + "published", + ], operations); + Assert.AreSequenceEqual( + [ + $"Copying file '{merged}' to '{Path.Combine(fixture.Root, "nested", "report.trx")}'", + $"Copying file '{attachment}' to '{Path.Combine(fixture.Root, "artifacts", "trace.log")}'", + ], fixture.Logs.Select(value => value.Message)); + fixture.FileSystem.Verify(value => value.DeleteFile(It.IsAny()), Times.Never); + fixture.FileSystem.Verify(value => value.MoveFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + fixture.Output.Verify( + value => value.DisplayAsync( + It.IsAny(), + It.Is(data => data.Text == string.Format( + CultureInfo.CurrentCulture, Policy.Resources.ExtensionResources.RetryArtifactsPublished, 2, fixture.Root)), + CancellationToken.None), Times.Once); + } + + [TestMethod] + public async Task Artifacts_TrxNamedAttachmentIsPreservedWithoutReportRegistration() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string attachment = Path.Combine(attempt, "diagnostics.trx"); + byte[] content = Encoding.UTF8.GetBytes("retry diagnostics"); + fixture.ExistingFiles[attachment] = content; + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([attachment]); + fixture.FileSystem.Setup(value => value.CopyFile(It.IsAny(), It.IsAny(), true)) + .Callback((source, destination, _) => fixture.ExistingFiles[destination] = fixture.GetBytes(source)); + + await RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, CancellationToken.None); + + Assert.IsTrue(fixture.ExistingFiles.ContainsKey(attachment), "A TRX-named attachment must remain at its recorded path."); + Assert.AreSequenceEqual(content, fixture.GetBytes(attachment)); + Assert.AreSequenceEqual(content, fixture.GetBytes(Path.Combine(fixture.Root, "diagnostics.trx"))); + fixture.FileSystem.Verify(value => value.DeleteFile(It.IsAny()), Times.Never); + } + + [TestMethod] + [DataRow("report.trx", true, DisplayName = "RetryArtifacts_FinalTrx")] + [DataRow("report.TRX", true, DisplayName = "RetryArtifacts_FinalTrxUppercase")] + [DataRow("report.xml", false, DisplayName = "RetryArtifacts_UnprocessedXml")] + [DataRow("report.ctrf.json", false, DisplayName = "RetryArtifacts_UnprocessedCtrf")] + [DataRow("report.html", false, DisplayName = "RetryArtifacts_UnprocessedHtml")] + [DataRow("trace.log", false, DisplayName = "RetryArtifacts_AttachmentLog")] + public async Task Artifacts_OnlyUnprocessedFinalTrxIsRemovedAfterAllCopies(string fileName, bool removeSource) + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string report = Path.Combine(attempt, "nested", fileName); + string attachment = Path.Combine(attempt, "artifacts", "attachment.txt"); + byte[] reportContents = Encoding.UTF8.GetBytes("report"); + byte[] attachmentContents = Encoding.UTF8.GetBytes("attachment"); + fixture.ExistingFiles[report] = reportContents; + fixture.ExistingFiles[attachment] = attachmentContents; + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([report, attachment]); + fixture.FileSystem.Setup(value => value.CopyFile(It.IsAny(), It.IsAny(), true)) + .Callback((source, destination, _) => + { + fixture.ExistingFiles[destination] = fixture.GetBytes(source); + fixture.Events.Add("copy:" + source); + }); + + await RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, new Dictionary(), [report], onTrxMoved: null, CancellationToken.None); + + Assert.AreEqual(!removeSource, fixture.ExistingFiles.ContainsKey(report)); + Assert.AreSequenceEqual(reportContents, fixture.GetBytes(Path.Combine(fixture.Root, "nested", fileName))); + Assert.AreSequenceEqual(attachmentContents, fixture.GetBytes(attachment)); + Assert.AreSequenceEqual(attachmentContents, fixture.GetBytes(Path.Combine(fixture.Root, "artifacts", "attachment.txt"))); + List expectedEvents = ["copy:" + report, "copy:" + attachment]; + if (removeSource) + { + expectedEvents.Add("delete:" + report); + } + + expectedEvents.Add("display"); + Assert.AreSequenceEqual(expectedEvents, fixture.Events); + } + + [TestMethod] + public async Task Artifacts_LaterCopyFailurePreservesFinalTrx() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string report = Path.Combine(attempt, "report.trx"); + string attachment = Path.Combine(attempt, "attachment.txt"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([report, attachment]); + var original = new IOException("attachment copy denied"); + fixture.FileSystem.Setup(value => value.CopyFile(attachment, Path.Combine(fixture.Root, "attachment.txt"), true)).Throws(original); + + IOException exception = await Assert.ThrowsExactlyAsync(() => RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, new Dictionary(), [report], onTrxMoved: null, CancellationToken.None)); + + Assert.AreSame(original, exception); + fixture.FileSystem.Verify(value => value.CopyFile(report, Path.Combine(fixture.Root, "report.trx"), true), Times.Once); + fixture.FileSystem.Verify(value => value.DeleteFile(It.IsAny()), Times.Never); + Assert.IsEmpty(fixture.Displays); + } + + [TestMethod] + public async Task Artifacts_DeleteFailureStopsBeforePublication() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string report = Path.Combine(attempt, "report.trx"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([report]); + var original = new IOException("delete denied"); + fixture.FileSystem.Setup(value => value.DeleteFile(report)).Throws(original); + + IOException exception = await Assert.ThrowsExactlyAsync(() => RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, new Dictionary(), [report], onTrxMoved: null, CancellationToken.None)); + + Assert.AreSame(original, exception); + fixture.FileSystem.Verify(value => value.CopyFile(report, Path.Combine(fixture.Root, "report.trx"), true), Times.Once); + Assert.IsEmpty(fixture.Displays); + } + + [TestMethod] + public async Task Artifacts_MovedTrxIsReportedAfterDeletionAndBeforePublication() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string source = Path.Combine(attempt, "report.trx"); + string destination = Path.Combine(fixture.Root, "report.trx"); + fixture.ExistingFiles[source] = Encoding.UTF8.GetBytes("report"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([source]); + fixture.FileSystem.Setup(value => value.CopyFile(source, destination, true)) + .Callback(() => fixture.ExistingFiles[destination] = fixture.GetBytes(source)); + List<(string Source, string Destination)> moved = []; + + await RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, new Dictionary(), [source], + (original, published) => + { + Assert.IsFalse(fixture.ExistingFiles.ContainsKey(original)); + Assert.IsTrue(fixture.ExistingFiles.ContainsKey(published)); + Assert.IsEmpty(fixture.Displays); + moved.Add((original, published)); + return Task.CompletedTask; + }, + CancellationToken.None); + + Assert.AreEqual((source, destination), Assert.ContainsSingle(moved)); + Assert.ContainsSingle(fixture.Displays); + } + + [TestMethod] + [DataRow(false, false, DisplayName = "RetryArtifacts_CopyFailureReplaysOriginalPath")] + [DataRow(true, false, DisplayName = "RetryArtifacts_PartialMoveReplaysBothPaths")] + [DataRow(false, true, DisplayName = "RetryArtifacts_ReplayFailurePreservesCopyException")] + public async Task Artifacts_PublicationFailureReplaysPendingNotificationsAndPreservesOriginalException(bool partialMove, bool replayFails) + { + using var fixture = new TrxBehaviorFixture(); + string retryRoot = Path.Combine(fixture.Root, "Retries", "run"); + string attempt = Path.Combine(retryRoot, "2"); + Directory.CreateDirectory(attempt); + try + { + string first = Path.Combine(attempt, "first.trx"); + string second = Path.Combine(attempt, "second.trx"); + string attachment = Path.Combine(attempt, "attachment.txt"); + File.WriteAllText(first, "first"); + File.WriteAllText(second, "second"); + File.WriteAllText(attachment, "attachment"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)) + .Returns(partialMove ? [first, second] : [first, attachment]); + var original = new IOException("artifact publication failed"); + fixture.FileSystem.Setup(value => value.CopyFile(It.IsAny(), It.IsAny(), true)) + .Callback((source, destination, _) => + { + if (!partialMove && source == attachment) + { + throw original; + } + + File.Copy(source, destination, overwrite: true); + }); + fixture.FileSystem.Setup(value => value.DeleteFile(It.IsAny())) + .Callback(path => + { + if (partialMove && path == second) + { + throw original; + } + + File.Delete(path); + }); + var protocol = new Mock(); + protocol.SetupGet(value => value.IsServerMode).Returns(true); + List replayed = []; + protocol.Setup(value => value.SendMessageAsync(It.IsAny())) + .Callback(new InvocationAction(call => replayed.Add((FileArtifactMessages)call.Arguments[0]))) + .Returns(() => replayFails ? Task.FromException(new IOException("replay failed")) : Task.CompletedTask); + fixture.Services.AddService(protocol.Object); + string manifests = RetryArtifactProcessor.GetDeferredTrxArtifactDirectory(retryRoot); + List artifacts = []; + foreach (string path in partialMove ? new[] { first, second } : [first]) + { + artifacts.Add(new RetryAttemptArtifact(path, "microsoft.testing.trx", 2, destinationPath: null)); + Assert.IsTrue(DotnetTestDataConsumer.TryDeferTrxArtifacts( + new FileArtifactMessages("execution", "instance", [new FileArtifactMessage(path, Path.GetFileName(path), null, null, null, "session", "microsoft.testing.trx")]), + attempt, + manifests)); + } + + var orchestrator = new RetryOrchestrator(fixture.Services); + System.Reflection.MethodInfo processArtifacts = typeof(RetryOrchestrator).GetMethod( + "ProcessArtifactsAsync", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + + IOException exception = await Assert.ThrowsExactlyAsync(() => (Task)processArtifacts.Invoke( + orchestrator, + [ + fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, artifacts, + 2, true, 2, 0, 1, false, TimeSpan.Zero, 2, attempt, fixture.Root, CancellationToken.None, + ])!); + + Assert.AreSame(original, exception); + string[] expected = partialMove ? [Path.Combine(fixture.Root, "first.trx"), second] : [first]; + Assert.AreSequenceEqual( + expected.OrderBy(path => path, StringComparer.Ordinal), + replayed.SelectMany(message => message.FileArtifacts).Select(artifact => artifact.FullPath!).OrderBy(path => path, StringComparer.Ordinal)); + Assert.IsTrue(expected.All(File.Exists)); + Assert.IsEmpty(fixture.Displays); + if (replayFails) + { + Assert.Contains( + log => log.Level == Microsoft.Testing.Platform.Logging.LogLevel.Warning && log.Message.Contains("Failed to replay retry artifacts", StringComparison.Ordinal), + fixture.Logs); + } + } + finally + { + Directory.Delete(fixture.Root, recursive: true); + } + } + + [TestMethod] + public async Task Artifacts_CopyFailureStopsBeforePublication() + { + using var fixture = new TrxBehaviorFixture(); + string attempt = Path.Combine(fixture.Root, "Retries", "run", "2"); + string file = Path.Combine(attempt, "report.trx"); + fixture.FileSystem.Setup(value => value.GetFiles(attempt, "*.*", SearchOption.AllDirectories)).Returns([file]); + var original = new IOException("copy denied"); + fixture.FileSystem.Setup(value => value.CopyFile(file, Path.Combine(fixture.Root, "report.trx"), true)).Throws(original); + + IOException exception = await Assert.ThrowsExactlyAsync(() => RetrySummaryReporter.MoveArtifactsAsync( + Mock.Of(), fixture.Output.Object, fixture.FileSystem.Object, fixture.Logger.Object, + attempt, fixture.Root, CancellationToken.None)); + + Assert.AreSame(original, exception); + Assert.IsEmpty(fixture.Displays); + Assert.AreEqual(LogLevel.Debug, Assert.ContainsSingle(fixture.Logs).Level); + fixture.FileSystem.Verify(value => value.DeleteFile(It.IsAny()), Times.Never); + } + + private sealed class TrxBehaviorFixture : IDisposable + { + public TrxBehaviorFixture() + { + LoggerFactory.Setup(value => value.CreateLogger(It.IsAny())).Returns(Logger.Object); + Logger.Setup(value => value.IsEnabled(It.IsAny())).Returns(true); + Logger.Setup(value => value.Log( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>())) + .Callback>((level, message, error, _) => Logs.Add((level, message, error))); + Logger.Setup(value => value.LogAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>())) + .Callback>((level, message, error, _) => Logs.Add((level, message, error))) + .Returns(Task.CompletedTask); + FileSystem.Setup(value => value.CreateDirectory(It.IsAny())).Returns(path => path); + FileSystem.Setup(value => value.DeleteFile(It.IsAny())) + .Callback(path => + { + Events.Add("delete:" + path); + ExistingFiles.Remove(path); + }); + Output.Setup(value => value.DisplayAsync( + It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((producer, data, token) => + { + Displays.Add((producer, data, token)); + Events.Add("display"); + }) + .Returns(Task.CompletedTask); + Services.AddServices( + [ + new TestCommandLineOptions([]), FileSystem.Object, LoggerFactory.Object, + Mock.Of(), Output.Object, + ]); + } + + public string Root { get; } = Path.Combine(Path.GetTempPath(), "retry-publication-" + Guid.NewGuid().ToString("N")); + + public ServiceProvider Services { get; } = new(); + + public Mock FileSystem { get; } = new(); + + public Mock Logger { get; } = new(); + + public Mock LoggerFactory { get; } = new(); + + public Mock Output { get; } = new(); + + public Dictionary ExistingFiles { get; } = []; + + public List Events { get; } = []; + + public List<(LogLevel Level, string Message, Exception? Error)> Logs { get; } = []; + + public List<(IOutputDeviceDataProducer Producer, IOutputDeviceData Data, CancellationToken Token)> Displays { get; } = []; + + public byte[] GetBytes(string path) => ExistingFiles[path]; + + public void Dispose() + { + if (Directory.Exists(Root)) + { + Directory.Delete(Root, recursive: true); + } + } + } +} diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxProcessLifetimeHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxProcessLifetimeHandlerTests.cs index b7a5e04b4b..7f07bf5bc4 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxProcessLifetimeHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxProcessLifetimeHandlerTests.cs @@ -9,6 +9,7 @@ using Microsoft.Testing.Extensions.UnitTests.Helpers; using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Configurations; +using Microsoft.Testing.Platform.Extensions.TestHostControllers; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.Messages; @@ -27,6 +28,47 @@ public sealed class TrxProcessLifetimeHandlerTests public TestContext TestContext { get; set; } = null!; + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task OnTestHostProcessExitedAsync_RegistersReportKindWithRetryOnlyWhenConfigured(bool retryEnabled) + { + string root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + string reportPath = Path.Combine(root, "report.trx"); + string manifestPath = Path.Combine(root, "artifacts.manifest"); + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable("TESTINGPLATFORM_RETRY_RECOVERED_ARTIFACT_MANIFEST")) + .Returns(retryEnabled ? manifestPath : null); + using MemoryStream manifest = new(); + var fileStream = new Mock(); + fileStream.SetupGet(value => value.Stream).Returns(manifest); + var fileSystem = new Mock(); + fileSystem.Setup(value => value.NewFileStream(manifestPath, FileMode.Append, FileAccess.Write, FileShare.Read)) + .Returns(fileStream.Object); + (TrxProcessLifetimeHandler handler, _, _, _) = CreateHandler(fileSystem.Object, environment.Object); + using (handler) + { + Type requestType = typeof(TrxProcessLifetimeHandler).Assembly.GetTypes().Single(type => type.Name == "ReportFileNameRequest"); + object request = Activator.CreateInstance(requestType, [reportPath])!; + await (Task)typeof(TrxProcessLifetimeHandler).GetMethod("CallbackAsync", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(handler, [request])!; + await handler.OnTestHostProcessExitedAsync(Mock.Of(), TestContext.CancellationToken); + } + + if (retryEnabled) + { + string[] entry = Encoding.UTF8.GetString(manifest.ToArray()).TrimEnd('\r', '\n').Split('\t'); + Assert.HasCount(2, entry); + Assert.AreEqual(reportPath, Encoding.UTF8.GetString(Convert.FromBase64String(entry[0]))); + Assert.AreEqual(TrxReportEngine.TrxArtifactKind, Encoding.UTF8.GetString(Convert.FromBase64String(entry[1]))); + } + else + { + Assert.AreEqual(0, manifest.Length); + fileSystem.Verify(value => value.NewFileStream(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + } + [TestMethod] public async Task BeforeTestHostProcessStartAsync_CreatesPipeBeforeSchedulingConnectionWait() { @@ -58,7 +100,9 @@ public async Task BeforeTestHostProcessStartAsync_UsesRuntimeAuthorizationAndPub } } - private static (TrxProcessLifetimeHandler Handler, NamedPipeServerEndpoint Endpoint, ServiceProvider ServiceProvider, DeferredTask Task) CreateHandler() + private static (TrxProcessLifetimeHandler Handler, NamedPipeServerEndpoint Endpoint, ServiceProvider ServiceProvider, DeferredTask Task) CreateHandler( + IFileSystem? customFileSystem = null, + IEnvironment? customEnvironment = null) { var commandLineOptions = new TestCommandLineOptions(new Dictionary { @@ -81,10 +125,10 @@ private static (TrxProcessLifetimeHandler Handler, NamedPipeServerEndpoint Endpo var handler = (TrxProcessLifetimeHandler)constructor.Invoke([ commandLineOptions, - environment.Object, + customEnvironment ?? environment.Object, loggerFactory.Object, new Mock().Object, - new Mock().Object, + customFileSystem ?? new Mock().Object, new Mock().Object, new Mock().Object, clock.Object, diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/DotnetTestDataConsumerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/DotnetTestDataConsumerTests.cs index f2178d7579..17ba8ff360 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/DotnetTestDataConsumerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/DotnetTestDataConsumerTests.cs @@ -3,17 +3,183 @@ using System.Reflection; +using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Extensions.Messages; +using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.IPC; using Microsoft.Testing.Platform.IPC.Models; +using Microsoft.Testing.Platform.Services; using Microsoft.Testing.Platform.TestHost; +using Moq; + namespace Microsoft.Testing.Platform.UnitTests; [TestClass] [UnsupportedOSPlatform("browser")] public sealed class DotnetTestDataConsumerTests { + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [DataRow("report.trx", true, true, DisplayName = "RetryArtifactManifest_Trx")] + [DataRow("report.TRX", true, true, DisplayName = "RetryArtifactManifest_UppercaseTrx")] + [DataRow("nested/report.trx", true, true, DisplayName = "RetryArtifactManifest_NestedTrx")] + [DataRow("report.txt", true, false, DisplayName = "RetryArtifactManifest_OtherArtifact")] + [DataRow("../attempt-sibling/report.trx", true, false, DisplayName = "RetryArtifactManifest_SiblingDirectory")] + [DataRow("report.trx", false, false, DisplayName = "RetryArtifactManifest_NoOptIn")] + public void TryDeferTrxArtifacts_OnlyDefersOwnedTrxAndPreservesWireIdentity(string relativePath, bool enabled, bool expectedDeferred) + { + string directory = Path.Combine(Path.GetTempPath(), $"deferred-trx-{Guid.NewGuid():N}"); + string attempt = Path.Combine(directory, "attempt"); + string manifests = Path.Combine(directory, "manifests"); + Directory.CreateDirectory(attempt); + try + { + string path = Path.GetFullPath(Path.Combine(attempt, relativePath.Replace('/', Path.DirectorySeparatorChar))); + var artifact = new FileArtifactMessage(path, "quoted \"report\"", "description", "test-uid", "test-name", "session", "microsoft.testing.trx"); + var message = new FileArtifactMessages("execution", "instance", [artifact]); + + bool deferred = DotnetTestDataConsumer.TryDeferTrxArtifacts(message, enabled ? attempt : null, manifests); + + Assert.AreEqual(expectedDeferred, deferred); + if (!expectedDeferred) + { + Assert.IsFalse(Directory.Exists(manifests)); + return; + } + + string manifest = Assert.ContainsSingle(Directory.GetFiles(manifests, "*.bin")); + Assert.IsEmpty(Directory.GetFiles(manifests, "*.tmp")); + FileArtifactMessages restored = DotnetTestDataConsumer.ReadDeferredTrxArtifacts(manifest); + Assert.AreEqual("execution", restored.ExecutionId); + Assert.AreEqual("instance", restored.InstanceId); + Assert.AreEqual(artifact, Assert.ContainsSingle(restored.FileArtifacts)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [TestMethod] + [DataRow(false, DisplayName = "RetryArtifactManifest_ControllerArtifact")] + [DataRow(true, DisplayName = "RetryArtifactManifest_SessionArtifact")] + public async Task ConsumeAsync_DeferredTrxIsRecordedInsteadOfSent(bool sessionScoped) + { + string directory = Path.Combine(Path.GetTempPath(), $"deferred-trx-{Guid.NewGuid():N}"); + string attempt = Path.Combine(directory, "attempt"); + string manifests = Path.Combine(directory, "manifests"); + Directory.CreateDirectory(attempt); + try + { + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID)).Returns("execution"); + environment.Setup(value => value.GetEnvironmentVariable(DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable)).Returns(attempt); + environment.Setup(value => value.GetEnvironmentVariable(DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable)).Returns(manifests); + (DotnetTestConnection connection, Mock client) = CreateConnection(environment.Object); + using DotnetTestConnection connectionOwnership = connection; + var consumer = new DotnetTestDataConsumer(connection, environment.Object); + var file = new FileInfo(Path.Combine(attempt, "report.trx")); + IData artifact = sessionScoped + ? new SessionFileArtifact(new SessionUid("session"), file, "report", "description", "microsoft.testing.trx") + : new FileArtifact(file, "report", "description", "microsoft.testing.trx"); + + await consumer.ConsumeAsync(Mock.Of(), artifact, TestContext.CancellationToken); + + Assert.IsEmpty(client.Invocations); + FileArtifactMessages recorded = DotnetTestDataConsumer.ReadDeferredTrxArtifacts(Assert.ContainsSingle(Directory.GetFiles(manifests, "*.bin"))); + Assert.AreEqual("execution", recorded.ExecutionId); + Assert.AreEqual(DotnetTestConnection.InstanceId, recorded.InstanceId); + FileArtifactMessage result = Assert.ContainsSingle(recorded.FileArtifacts); + Assert.AreEqual(file.FullName, result.FullPath); + Assert.AreEqual(sessionScoped ? "session" : string.Empty, result.SessionUid); + Assert.AreEqual("report", result.DisplayName); + Assert.AreEqual("description", result.Description); + Assert.AreEqual("microsoft.testing.trx", result.Kind); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [TestMethod] + public async Task ConsumeAsync_DeferredTestAttachmentStillStreamsTheTestResult() + { + string directory = Path.Combine(Path.GetTempPath(), $"deferred-trx-{Guid.NewGuid():N}"); + string attempt = Path.Combine(directory, "attempt"); + string manifests = Path.Combine(directory, "manifests"); + Directory.CreateDirectory(attempt); + try + { + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID)).Returns("execution"); + environment.Setup(value => value.GetEnvironmentVariable(DotnetTestDataConsumer.DeferredTrxRootEnvironmentVariable)).Returns(attempt); + environment.Setup(value => value.GetEnvironmentVariable(DotnetTestDataConsumer.DeferredTrxDirectoryEnvironmentVariable)).Returns(manifests); + (DotnetTestConnection connection, Mock client) = CreateConnection(environment.Object); + using DotnetTestConnection connectionOwnership = connection; + var consumer = new DotnetTestDataConsumer(connection, environment.Object); + var file = new FileInfo(Path.Combine(attempt, "attachment.trx")); + var update = new TestNodeUpdateMessage(new SessionUid("session"), new TestNode + { + Uid = new TestNodeUid("uid"), + DisplayName = "DisplayName", + Properties = new PropertyBag(PassedTestNodeStateProperty.CachedInstance, new FileArtifactProperty(file, "attachment")), + }); + + await consumer.ConsumeAsync(Mock.Of(), update, TestContext.CancellationToken); + + object request = Assert.ContainsSingle(client.Invocations).Arguments[0]; + TestResultMessages results = Assert.IsInstanceOfType(request); + Assert.AreEqual("uid", Assert.ContainsSingle(results.SuccessfulTestMessages).Uid); + FileArtifactMessage recorded = Assert.ContainsSingle(DotnetTestDataConsumer.ReadDeferredTrxArtifacts( + Assert.ContainsSingle(Directory.GetFiles(manifests, "*.bin"))).FileArtifacts); + Assert.AreEqual(file.FullName, recorded.FullPath); + Assert.AreEqual("uid", recorded.TestUid); + Assert.AreEqual("DisplayName", recorded.TestDisplayName); + Assert.AreEqual("session", recorded.SessionUid); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [TestMethod] + public void TryDeferTrxArtifacts_WriteFailureIsNotReportedAsSuccess() + { + string directory = Path.Combine(Path.GetTempPath(), $"deferred-trx-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + string blocked = Path.Combine(directory, "blocked"); + File.WriteAllText(blocked, "not a directory"); + var message = new FileArtifactMessages("execution", "instance", + [new FileArtifactMessage(Path.Combine(directory, "report.trx"), "report", null, null, null, null, null)]); + + Assert.ThrowsExactly(() => DotnetTestDataConsumer.TryDeferTrxArtifacts(message, directory, blocked)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private (DotnetTestConnection Connection, Mock Client) CreateConnection(IEnvironment environment) + { + ITestApplicationModuleInfo module = Mock.Of(); + var commandLine = new CommandLineHandler(new CommandLineParseResult(null, [], []), [], [], module, Mock.Of()); + var cancellation = new Mock(); + cancellation.SetupGet(value => value.CancellationToken).Returns(TestContext.CancellationToken); + var connection = new DotnetTestConnection(commandLine, environment, module, cancellation.Object); + // The core's embedded transport interface is distinct from this assembly's linked IPC copy. + FieldInfo transport = typeof(DotnetTestConnection).GetField("_transportClient", BindingFlags.Instance | BindingFlags.NonPublic)!; + var client = (Mock)Activator.CreateInstance(typeof(Mock<>).MakeGenericType(transport.FieldType))!; + transport.SetValue(connection, client.Object); + return (connection, client); + } + [TestMethod] [DynamicData(nameof(DuplicateSingleOrDefaultProperties))] public void GetTestNodeDetails_WithDuplicateSingleOrDefaultProperty_ThrowsInvalidOperationException(Type propertyType, IProperty firstProperty, IProperty secondProperty)