diff --git a/src/Adapter/MSTest.TestAdapter/PACKAGE.md b/src/Adapter/MSTest.TestAdapter/PACKAGE.md index 9ee9d77660..bee1032a6b 100644 --- a/src/Adapter/MSTest.TestAdapter/PACKAGE.md +++ b/src/Adapter/MSTest.TestAdapter/PACKAGE.md @@ -39,6 +39,22 @@ as `Playwright`, produce a warning and are not applied by MSTest. Use the extens native Microsoft.Testing.Platform configuration when available. VSTest loggers, data collectors, and unsupported `RunConfiguration` entries retain their own warnings. +## Result file attachments + +When running on Microsoft.Testing.Platform, `TestContext.AddResultFile` registers +an existing file as a test attachment. MSTest preserves successfully copied +attachments in visible `MSTest-` folders under the configured results +directory so the published paths remain readable after the test host exits. +Original files are not moved or deleted by this copying step. + +These copies are final test results: apply your results-directory retention policy +to remove them when they are no longer needed. TRX reporting can create an +additional copy in its own attachment layout; follow the report's references +rather than selecting a file by name from the entire results directory. +Retry tooling can also publish additional copies from the final attempt. +If an attachment cannot be copied, MSTest reports its original path so consumers +can surface their usual missing-file or copy-failure diagnostics. + ## Documentation For installation and configuration guidance, see . diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestTestFramework.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestTestFramework.cs index d715683fff..8f8b5155dc 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestTestFramework.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestTestFramework.cs @@ -45,6 +45,7 @@ internal sealed class MSTestTestFramework : ITestFramework, IDataProducer, IDisp private readonly CountdownEvent _incomingRequestCounter = new(1); private int _nextResultFileStagingDirectory; private int _resultFilesStagingDirectoryCreated; + private int _hasDurableResultFiles; private bool? _isTrxEnabled; private bool _isDisposed; private SessionUid? _sessionUid; @@ -59,9 +60,10 @@ public MSTestTestFramework(MSTestExtension extension, Func _configuration = new(serviceProvider.GetConfiguration()); _loggerFactory = serviceProvider.GetRequiredService(); _gracefulStopCapability = (MSTestGracefulStopTestExecutionCapability)capabilities.GetCapability()!; + // Retained roots need more entropy than a temporary cache without excessive legacy path growth. _resultFilesStagingDirectory = Path.Combine( - serviceProvider.GetConfiguration().GetTestResultDirectory(), - $".mstest-{Guid.NewGuid():N}"[..16]); + Path.GetFullPath(serviceProvider.GetConfiguration().GetTestResultDirectory()), + $"MSTest-{Guid.NewGuid().ToString("N")[..20]}"); ((Microsoft.Testing.Platform.Services.ServiceProvider)serviceProvider) .AddService(new ResultFilesStagingDirectoryCleanup(CleanupResultFilesStagingDirectory)); PlatformServiceProvider.Instance.AdapterTraceLogger = new MTPTraceLogger(_loggerFactory.CreateLogger("mstest-trace")); @@ -286,6 +288,7 @@ private void StageResultFiles(TestResult result) GetPathForFileSystemAccess(stagedPath)); durableResultFiles.Add(stagedPath); + Volatile.Write(ref _hasDurableResultFiles, 1); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { @@ -355,7 +358,9 @@ private static bool ContainsRelativePathSegments(string path) private void CleanupResultFilesStagingDirectory() { - if (Volatile.Read(ref _resultFilesStagingDirectoryCreated) == 0) + // Published copies must outlive the host; only unsuccessful staging attempts can be removed. + if (Volatile.Read(ref _resultFilesStagingDirectoryCreated) == 0 + || Volatile.Read(ref _hasDurableResultFiles) != 0) { return; } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ResultFileTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ResultFileTests.cs new file mode 100644 index 0000000000..9e1558d146 --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ResultFileTests.cs @@ -0,0 +1,383 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; + +using Microsoft.Testing.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.ServerMode.IntegrationTests.Messages.V100; + +using MSTest.Acceptance.IntegrationTests.Messages.V100; + +namespace MSTest.Acceptance.IntegrationTests; + +[TestClass] +public sealed class ResultFileTests : ServerModeTestsBase +{ + private const string SourceDirectoryVariable = "MSTEST_RESULT_FILE_SOURCE_DIRECTORY"; + private const string WaitForCancellationVariable = "MSTEST_RESULT_FILE_WAIT_FOR_CANCELLATION"; + private const string FileNameVariable = "MSTEST_RESULT_FILE_NAME"; + private const string DefaultFileName = "attachment.txt"; + private const int WindowsMaxPath = 260; + private static readonly Dictionary ExpectedAttachments = new(StringComparer.Ordinal) + { + ["FirstAttachment"] = "first attachment", + ["SecondAttachment"] = "second attachment", + }; + + public TestContext TestContext { get; set; } + + public static IEnumerable<(string Tfm, bool RelativeResultsDirectory, bool EnableTrx, bool LongResultsDirectory)> DotnetTestCases + { + get + { + foreach (string tfm in TargetFrameworks.All) + { + foreach (bool relativeResultsDirectory in new[] { false, true }) + { + foreach (bool enableTrx in new[] { false, true }) + { + yield return (tfm, relativeResultsDirectory, enableTrx, false); + } + } + + if (TargetFrameworks.NetFramework.Contains(tfm)) + { + yield return (tfm, false, true, true); + } + } + } + } + + public static IEnumerable<(string Tfm, bool RelativeResultsDirectory)> JsonRpcTestCases + => from tfm in TargetFrameworks.All + from relativeResultsDirectory in new[] { false, true } + select (tfm, relativeResultsDirectory); + + [TestMethod] + [DynamicData(nameof(DotnetTestCases))] + public async Task DotnetTest_PublishedResultFiles_SurviveProcessExit(string tfm, bool relativeResultsDirectory, bool enableTrx, bool longResultsDirectory) + { + string resultsName = longResultsDirectory + ? $"lp-{Guid.NewGuid().ToString("N")[..12]}" + : $"Test Results-{Guid.NewGuid():N}"; + string resultsRoot = Path.Combine(AssetFixture.TargetAssetPath, resultsName); + string resultsDirectory = resultsRoot; + if (longResultsDirectory) + { + // Leave room for .NET Framework deployment folders; cross MAX_PATH with the copied file name. + resultsDirectory = resultsRoot.Length < 180 + ? Path.Combine(resultsRoot, new string('r', 180 - resultsRoot.Length - 1)) + : resultsRoot; + Assert.IsLessThanOrEqualTo(180, resultsDirectory.Length); + } + + string sourceDirectory = Path.Combine(AssetFixture.TargetAssetPath, $"s-{Guid.NewGuid():N}"); + string fileName = longResultsDirectory ? $"attachment-{new string('r', 45)}.txt" : DefaultFileName; + if (longResultsDirectory) + { + Assert.IsLessThan(WindowsMaxPath, Path.Combine(sourceDirectory, "SecondAttachment", fileName).Length); + } + + var host = TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.ProjectName, tfm); + string module = TargetFrameworks.NetFramework.Contains(tfm) + ? Path.GetFileName(host.FullName) + : $"{TestAssetFixture.ProjectName}.dll"; + string resultsArgument = relativeResultsDirectory ? Path.GetRelativePath(AssetFixture.TargetAssetPath, resultsDirectory) : resultsDirectory; + string trxArgument = enableTrx ? "--report-trx --report-trx-filename results.trx" : string.Empty; + + try + { + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"test --test-modules \"{module}\" --root-directory \"{host.DirectoryName}\" --results-directory \"{resultsArgument}\" --no-ansi --progress off {trxArgument}", + workingDirectory: AssetFixture.TargetAssetPath, + environmentVariables: new() + { + [SourceDirectoryVariable] = sourceDirectory, + ["DOTNET_CLI_UI_LANGUAGE"] = "en-US", + ["TESTINGPLATFORM_UI_LANGUAGE"] = "en-US", + [WaitForCancellationVariable] = "0", + [FileNameVariable] = fileName, + }, + failIfReturnValueIsNotZero: false, + warnAsError: false, + suppressPreviewDotNetMessage: false, + useMultithreadedMSBuild: false, + cancellationToken: TestContext.CancellationToken); + + result.AssertExitCodeIs(ExitCode.Success); + result.AssertOutputContains("total: 2"); + result.AssertOutputContains("succeeded: 2"); + (string TestName, string Path)[] attachments = [.. Regex.Matches( + result.StandardOutput, + @"For test '(?[^']+)': (?[^\r\n]+)") + .Select(match => (match.Groups["test"].Value, Path.GetFullPath(match.Groups["path"].Value.Trim(), AssetFixture.TargetAssetPath)))]; + + AssertPublishedAttachments(attachments, resultsDirectory, longResultsDirectory, fileName); + AssertOriginalAttachments(sourceDirectory, fileName); + if (enableTrx) + { + AssertTrxAttachments(Path.Combine(resultsDirectory, "results.trx"), resultsDirectory); + } + } + finally + { + DeleteDirectory(sourceDirectory); + DeleteDirectory(resultsRoot); + } + } + + [TestMethod] + [DynamicData(nameof(JsonRpcTestCases))] + public async Task JsonRpc_PublishedResultFiles_SurviveProcessExit(string tfm, bool relativeResultsDirectory) + { + string resultsName = $"Test Results-{Guid.NewGuid():N}"; + string resultsDirectory = Path.Combine(AssetFixture.TargetAssetPath, resultsName); + string sourceDirectory = Path.Combine(AssetFixture.TargetAssetPath, $"sources-{Guid.NewGuid():N}"); + var host = TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.ProjectName, tfm); + string resultsArgument = relativeResultsDirectory ? resultsName : resultsDirectory; + + try + { + using TestingPlatformClient client = await StartAsServerAndConnectToTheClientAsync( + host, + new Dictionary + { + [SourceDirectoryVariable] = sourceDirectory, + [WaitForCancellationVariable] = "0", + [FileNameVariable] = DefaultFileName, + }, + $"--results-directory \"{resultsArgument}\"", + workingDirectory: AssetFixture.TargetAssetPath); + await client.Initialize(); + TestNodeUpdateCollector collector = new(); + ResponseListener listener = await client.RunTests(Guid.NewGuid(), collector.CollectNodeUpdates); + await listener.WaitCompletion().WaitAsync(TimeSpan.FromMinutes(3), TestContext.CancellationToken); + await client.Exit(); + Assert.AreEqual(0, await client.WaitServerProcessExit(TestContext.CancellationToken)); + + TestNode[] results = collector.TestNodeUpdates + .Select(update => update.Node) + .Where(node => node.ExecutionState == "passed") + .ToArray(); + Assert.HasCount(ExpectedAttachments.Count, results); + Assert.HasCount(ExpectedAttachments.Count, results.Select(node => node.Uid).Distinct(StringComparer.Ordinal)); + (string TestName, string Path)[] attachments = [.. results.SelectMany(node => node.Properties + .Where(property => property.Key.StartsWith("attachments.", StringComparison.Ordinal) + && property.Key.EndsWith(".uri", StringComparison.Ordinal)) + .Select(property => (node.DisplayName, property.Value.ToString())))]; + + AssertPublishedAttachments(attachments, resultsDirectory); + AssertOriginalAttachments(sourceDirectory); + } + finally + { + DeleteDirectory(sourceDirectory); + DeleteDirectory(resultsDirectory); + } + } + + [TestMethod] + public async Task Trx_AbortedRun_PreservesRecoveredResultFiles() + { + string resultsDirectory = Path.Combine(AssetFixture.TargetAssetPath, $"results-{Guid.NewGuid():N}"); + string sourceDirectory = Path.Combine(AssetFixture.TargetAssetPath, $"sources-{Guid.NewGuid():N}"); + var host = TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.ProjectName, TargetFrameworks.NetCurrent); + string settings = Path.Combine(AssetFixture.TargetAssetPath, "ordered.runsettings"); + + try + { + TestHostResult result = await host.ExecuteAsync( + $"--settings \"{settings}\" --report-trx --report-trx-filename recovered.trx --results-directory \"{resultsDirectory}\" --timeout 15s", + new() + { + [SourceDirectoryVariable] = sourceDirectory, + [WaitForCancellationVariable] = "1", + [FileNameVariable] = DefaultFileName, + ["TESTINGPLATFORM_UI_LANGUAGE"] = "en-US", + }, + cancellationToken: TestContext.CancellationToken); + + result.AssertExitCodeIs(ExitCode.TestHostProcessExitedNonGracefully); + Assert.IsTrue(File.Exists(Path.Combine(sourceDirectory, "waiting-for-cancellation")), "The second test must reach its cancellation rendezvous."); + result.AssertOutputContains("recovered 1 test result(s)"); + result.AssertOutputContains("Test application process didn't exit gracefully, exit code is '3'"); + result.AssertOutputDoesNotContain("The attachment will be skipped."); + XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; + var document = XDocument.Load(Path.Combine(resultsDirectory, "recovered.trx")); + Assert.AreEqual("Failed", document.Descendants(ns + "ResultSummary").Single().Attribute("outcome")!.Value); + XElement recovered = Assert.ContainsSingle( + testResult => testResult.Attribute("testName")?.Value == "FirstAttachment", + document.Descendants(ns + "UnitTestResult")); + AssertTrxResultAttachment(document, recovered, resultsDirectory); + } + finally + { + DeleteDirectory(sourceDirectory); + DeleteDirectory(resultsDirectory); + } + } + + private static void AssertPublishedAttachments( + (string TestName, string Path)[] attachments, + string resultsDirectory, + bool requireLongPaths = false, + string expectedFileName = DefaultFileName) + { + Assert.AreSequenceEqual( + ExpectedAttachments.Keys.Order(StringComparer.Ordinal), + attachments.Select(attachment => attachment.TestName).Order(StringComparer.Ordinal)); + Assert.HasCount(ExpectedAttachments.Count, attachments.Select(attachment => attachment.Path).Distinct(StringComparer.Ordinal)); + foreach ((string testName, string path) in attachments) + { + Assert.StartsWith(Path.GetFullPath(resultsDirectory) + Path.DirectorySeparatorChar, Path.GetFullPath(path)); + Assert.AreEqual(expectedFileName, Path.GetFileName(path)); + Assert.IsTrue(File.Exists(path), $"Published attachment for '{testName}' must remain readable after host exit: '{path}'."); + Assert.AreEqual(ExpectedAttachments[testName], File.ReadAllText(path)); + if (requireLongPaths) + { + Assert.IsGreaterThan(WindowsMaxPath, Path.GetFullPath(path).Length); + } + } + } + + private static void AssertOriginalAttachments(string sourceDirectory, string fileName = DefaultFileName) + { + foreach (KeyValuePair attachment in ExpectedAttachments) + { + Assert.AreEqual( + attachment.Value, + File.ReadAllText(Path.Combine(sourceDirectory, attachment.Key, fileName))); + } + } + + private static void AssertTrxAttachments(string trxPath, string resultsDirectory) + { + XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; + var document = XDocument.Load(trxPath); + XElement[] results = [.. document.Descendants(ns + "UnitTestResult")]; + Assert.AreSequenceEqual( + ExpectedAttachments.Keys.Order(StringComparer.Ordinal), + results.Select(result => result.Attribute("testName")!.Value).Order(StringComparer.Ordinal)); + foreach (XElement result in results) + { + AssertTrxResultAttachment(document, result, resultsDirectory); + } + } + + private static void AssertTrxResultAttachment(XDocument document, XElement result, string resultsDirectory) + { + XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; + string deploymentRoot = document.Descendants(ns + "Deployment").Single().Attribute("runDeploymentRoot")!.Value; + Assert.AreEqual("Passed", result.Attribute("outcome")!.Value); + XElement resultFile = Assert.ContainsSingle(result.Descendants(ns + "ResultFile")); + string path = Path.Combine( + resultsDirectory, + deploymentRoot, + "In", + result.Attribute("relativeResultsDirectory")!.Value, + resultFile.Attribute("path")!.Value.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)); + Assert.AreEqual(ExpectedAttachments[result.Attribute("testName")!.Value], File.ReadAllText(path)); + } + + private static void DeleteDirectory(string path) + { + if (Directory.Exists(path)) + { + Directory.Delete(path, recursive: true); + } + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase + { + public const string ProjectName = "MSTestResultFiles"; + + public string TargetAssetPath => GetAssetPath(ProjectName); + + public override (string ID, string Name, string Code) GetAssetsToGenerate() + => (ProjectName, ProjectName, SourceCode + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + + private const string SourceCode = """ +#file MSTestResultFiles.csproj + + + Exe + true + $TargetFrameworks$ + latest + + + + + + + +#file ordered.runsettings + + + true + false + + + +#file global.json +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} + +#file AttachmentTests.cs +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MSTestResultFiles; + +[TestClass] +public sealed class AttachmentTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void FirstAttachment() => AddAttachment(nameof(FirstAttachment), "first attachment"); + + [TestMethod] + public async Task SecondAttachment() + { + if (Environment.GetEnvironmentVariable("MSTEST_RESULT_FILE_WAIT_FOR_CANCELLATION") == "1") + { + string sourceDirectory = Environment.GetEnvironmentVariable("MSTEST_RESULT_FILE_SOURCE_DIRECTORY") + ?? throw new InvalidOperationException("MSTEST_RESULT_FILE_SOURCE_DIRECTORY is not set."); + Directory.CreateDirectory(sourceDirectory); + File.WriteAllText(Path.Combine(sourceDirectory, "waiting-for-cancellation"), "ready"); + await Task.Delay(Timeout.Infinite, TestContext.CancellationToken); + } + else + { + AddAttachment(nameof(SecondAttachment), "second attachment"); + } + } + + private void AddAttachment(string testName, string content) + { + string sourceDirectory = Environment.GetEnvironmentVariable("MSTEST_RESULT_FILE_SOURCE_DIRECTORY") + ?? throw new InvalidOperationException("MSTEST_RESULT_FILE_SOURCE_DIRECTORY is not set."); + string directory = Path.Combine(sourceDirectory, testName); + Directory.CreateDirectory(directory); + string fileName = Environment.GetEnvironmentVariable("MSTEST_RESULT_FILE_NAME") + ?? throw new InvalidOperationException("MSTEST_RESULT_FILE_NAME is not set."); + string path = Path.Combine(directory, fileName); + File.WriteAllText(path, content); + TestContext.AddResultFile(path); + } +} +"""; + } +} diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TrxReportTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TrxReportTests.cs index a28190e2a8..5b46e3459a 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TrxReportTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TrxReportTests.cs @@ -115,7 +115,10 @@ public async Task TrxReport_ResultFilesUnderTestResultsDirectory_SurviveDeployme Assert.HasCount(2, copiedResultFiles); Assert.AreSequenceEqual(["first attachment", "second attachment"], copiedResultFiles.Select(File.ReadAllText).Order(StringComparer.Ordinal).ToArray()); Assert.AreSequenceEqual(["attachment.txt", "attachment_1.txt"], copiedResultFiles.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray()); - Assert.IsEmpty(Directory.GetDirectories(testResultsPath, ".mstest-*", SearchOption.TopDirectoryOnly)); + string publishedResultDirectory = Assert.ContainsSingle(Directory.GetDirectories(testResultsPath, "MSTest-*", SearchOption.TopDirectoryOnly)); + string[] publishedResultFiles = Directory.GetFiles(publishedResultDirectory, "*", SearchOption.AllDirectories); + Assert.HasCount(2, publishedResultFiles); + Assert.AreSequenceEqual(["first attachment", "second attachment"], publishedResultFiles.Select(File.ReadAllText).Order(StringComparer.Ordinal).ToArray()); } finally { @@ -152,7 +155,7 @@ public async Task TrxReport_MissingResultFile_PreservesWarningAndSkipsResultFile XElement warningRunInfo = trxDocument.Descendants(ns + "RunInfo").Single(runInfo => runInfo.Attribute("outcome")?.Value == "Warning"); Assert.Contains("missing-result-file.txt", warningRunInfo.Value); - Assert.IsEmpty(Directory.GetDirectories(testResultsPath, ".mstest-*", SearchOption.TopDirectoryOnly)); + Assert.IsEmpty(Directory.GetDirectories(testResultsPath, "MSTest-*", SearchOption.TopDirectoryOnly)); } finally { diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/ServerModeTestsBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/ServerModeTestsBase.cs index 2bb371ba6c..1b2fbca245 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/ServerModeTestsBase.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/ServerModeTestsBase.cs @@ -25,7 +25,11 @@ namespace MSTest.Acceptance.IntegrationTests.Messages.V100; protected Task StartAsServerAndConnectToTheClientAsync(TestHost testHost) => StartAsServerAndConnectToTheClientAsync(testHost, additionalEnvironmentVariables: null); - protected async Task StartAsServerAndConnectToTheClientAsync(TestHost testHost, IReadOnlyDictionary? additionalEnvironmentVariables) + protected async Task StartAsServerAndConnectToTheClientAsync( + TestHost testHost, + IReadOnlyDictionary? additionalEnvironmentVariables, + string? additionalArguments = null, + string? workingDirectory = null) { var environmentVariables = new Dictionary(DefaultEnvironmentVariables); foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) @@ -63,7 +67,9 @@ protected async Task StartAsServerAndConnectToTheClientAs OnErrorOutput = (_, output) => builder.AppendLine(CultureInfo.InvariantCulture, $"OnErrorOutput:\n{output}"), OnExit = (processHandle, exitCode) => builder.AppendLine(CultureInfo.InvariantCulture, $"OnExit: exit code '{exitCode}'"), - Arguments = $"--server --client-host localhost --client-port {((IPEndPoint)tcpListener.LocalEndpoint).Port} --diagnostic --diagnostic-verbosity trace", + Arguments = $"--server --client-host localhost --client-port {((IPEndPoint)tcpListener.LocalEndpoint).Port} --diagnostic --diagnostic-verbosity trace" + + (additionalArguments is null ? string.Empty : $" {additionalArguments}"), + WorkingDirectory = workingDirectory, EnvironmentVariables = environmentVariables, }; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestNode.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestNode.cs index eedbceaa1f..ecb20589d0 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestNode.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestNode.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Microsoft.Testing.Platform.ServerMode.IntegrationTests.Messages.V100; @@ -26,4 +27,8 @@ public sealed record TestNode string NodeType, [property: JsonProperty("execution-state")] - string ExecutionState); + string ExecutionState) +{ + [JsonExtensionData] + public Dictionary Properties { get; set; } = []; +} diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestResultFilesTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/MSTestResultFilesTests.cs new file mode 100644 index 0000000000..a6a3314907 --- /dev/null +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestResultFilesTests.cs @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using AwesomeAssertions; + +using Microsoft.Testing.Platform.Capabilities.TestFramework; +using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Configurations; +using Microsoft.Testing.Platform.Extensions.Messages; +using Microsoft.Testing.Platform.Extensions.OutputDevice; +using Microsoft.Testing.Platform.Extensions.TestFramework; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Logging; +using Microsoft.Testing.Platform.Messages; +using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.Requests; +using Microsoft.Testing.Platform.Services; +using Microsoft.Testing.Platform.Telemetry; +using Microsoft.Testing.Platform.TestHost; +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using TestFramework.ForTestingMSTest; + +using NativeConfiguration = Microsoft.Testing.Platform.Configurations.IConfiguration; +using NativeServiceProvider = Microsoft.Testing.Platform.Services.ServiceProvider; +using TestSessionContext = Microsoft.Testing.Platform.TestHost.TestSessionContext; + +namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests; + +public sealed class MSTestResultFilesTests : TestContainer +{ + public async Task PublishedResultFilesSurviveFrameworkAndServiceDisposal() + { + foreach (bool missingFirst in new[] { false, true }) + { + using var harness = new NativeHarness(); + string source = Path.Combine(harness.Directory, "original.bin"); + string missing = Path.Combine(harness.Directory, "missing.bin"); + byte[] bytes = [0, 17, 128, 255, 42]; + File.WriteAllBytes(source, bytes); + harness.SetAttachmentPaths(missingFirst ? missing : source, missingFirst ? source : missing); + await harness.OpenAsync(); + + await harness.RunAsync(); + + TestNodeUpdateMessage result = harness.Messages.OfType() + .Single(message => !message.TestNode.Properties.Any()); + result.TestNode.Properties.Any().Should().BeTrue(); + FileArtifactProperty[] artifacts = result.TestNode.Properties.OfType().ToArray(); + artifacts.Should().HaveCount(2); + string staged = artifacts.Single(artifact => artifact.FileInfo.Name == "original.bin").FileInfo.FullName; + staged.Should().NotBe(source); + Path.GetFileName(staged).Should().Be("original.bin"); + File.ReadAllBytes(staged).Should().Equal(bytes); + FileArtifactProperty missingArtifact = artifacts.Single(artifact => artifact.FileInfo.Name == "missing.bin"); + missingArtifact.FileInfo.FullName.Should().Be(missing); + missingArtifact.FileInfo.Exists.Should().BeFalse(); + + await harness.CloseAsync(); + harness.Framework.Dispose(); + harness.Framework.Dispose(); + File.Exists(staged).Should().BeTrue("published result files outlive framework disposal"); + File.ReadAllBytes(source).Should().Equal(bytes); + foreach (IDisposable cleanup in harness.Services.Services.OfType()) + { + cleanup.Dispose(); + cleanup.Dispose(); + } + + File.Exists(staged).Should().BeTrue("published result files outlive service disposal"); + File.ReadAllBytes(staged).Should().Equal(bytes); + string resultDirectory = Directory.GetDirectories(harness.Directory, "MSTest-*").Single(); + Path.GetFileName(resultDirectory).Should().MatchRegex(@"^MSTest-[0-9a-f]{20}$"); + } + } + + public async Task DisposalPreservesOpenPublishedAttachmentsWithoutWarnings() + { + using var harness = new NativeHarness(); + string source = Path.Combine(harness.Directory, "locked-source.bin"); + string missing = Path.Combine(harness.Directory, "missing.bin"); + File.WriteAllBytes(source, [17, 23, 42]); + harness.SetAttachmentPaths(source, missing); + List warnings = harness.CaptureWarnings(); + await harness.OpenAsync(); + await harness.RunAsync(); + string staged = harness.Messages.OfType() + .SelectMany(message => message.TestNode.Properties.OfType()) + .Single(artifact => artifact.FileInfo.Name == "locked-source.bin").FileInfo.FullName; + await harness.CloseAsync(); + + using (var held = new FileStream(staged, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + harness.Framework.Dispose(); + File.Exists(staged).Should().BeTrue(); + warnings.Should().BeEmpty(); + + foreach (IDisposable cleanup in harness.Services.Services.OfType()) + { + cleanup.Dispose(); + cleanup.Dispose(); + } + + File.Exists(staged).Should().BeTrue(); + warnings.Should().BeEmpty(); + } + + File.ReadAllBytes(staged).Should().Equal(17, 23, 42); + File.ReadAllBytes(source).Should().Equal(17, 23, 42); + } + + public async Task FailedResultFileCopiesRemainEligibleForCleanup() + { + using var harness = new NativeHarness(); + string missing = Path.Combine(harness.Directory, "missing.bin"); + harness.SetAttachmentPaths(missing, missing); + List warnings = harness.CaptureWarnings(); + await harness.OpenAsync(); + await harness.RunAsync(); + await harness.CloseAsync(); + FileArtifactProperty[] artifacts = harness.Messages.OfType() + .SelectMany(message => message.TestNode.Properties.OfType()) + .ToArray(); + artifacts.Should().HaveCount(2); + artifacts.Should().OnlyContain(artifact => artifact.FileInfo.FullName == missing && !artifact.FileInfo.Exists); + string resultDirectory = Directory.GetDirectories(harness.Directory, "MSTest-*").Single(); + string heldPath = Path.Combine(resultDirectory, "cleanup-lock.bin"); + File.WriteAllBytes(heldPath, [17, 23, 42]); + + using (var held = new FileStream(heldPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + foreach (IDisposable cleanup in harness.Services.Services.OfType()) + { + cleanup.Dispose(); + cleanup.Dispose(); + } + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + File.Exists(heldPath).Should().BeTrue(); + warnings.Should().ContainSingle(); + warnings[0].Should().StartWith("Failed to delete result-file staging directory '").And.Contain("IOException"); + } + else + { + File.Exists(heldPath).Should().BeFalse(); + warnings.Should().BeEmpty(); + } + } + + harness.Framework.Dispose(); + harness.Framework.Dispose(); + Directory.GetDirectories(harness.Directory, "MSTest-*").Should().BeEmpty(); + File.Exists(missing).Should().BeFalse(); + } + + private sealed class NativeHarness : IDisposable + { + private readonly IPlatformServiceProvider _previous; + private readonly Mock _files = new(); + private readonly Mock _options = new(); + + internal NativeHarness() + { + Directory = Path.Combine(Path.GetTempPath(), "native-result-files-" + Guid.NewGuid().ToString("N")); + System.IO.Directory.CreateDirectory(Directory); + _previous = PlatformServiceProvider.Instance; + PlatformServiceProvider.Instance = null!; + var configuration = new Mock(); + configuration.Setup(value => value[PlatformConfigurationConstants.PlatformResultDirectory]).Returns(Directory); + configuration.Setup(value => value[PlatformConfigurationConstants.PlatformCurrentWorkingDirectory]).Returns(Directory); + var loggerFactory = new Mock(); + loggerFactory.Setup(value => value.CreateLogger(It.IsAny())).Returns(Mock.Of()); + string[]? noArguments = null; + _options.Setup(value => value.TryGetOptionArgumentList(It.IsAny(), out noArguments)).Returns(false); + Services = new NativeServiceProvider(); + Services.AddServices([ + configuration.Object, _options.Object, _files.Object, loggerFactory.Object, + Mock.Of(), new ClientInfoService("unit-client", "1.0", new ClientCapabilitiesService(false)), + Mock.Of(), Mock.Of(), + ]); + Framework = new(new MSTestExtension(), () => [typeof(AttachmentFixture).Assembly], Services, + new TestFrameworkCapabilities(MSTestGracefulStopTestExecutionCapability.Create())); + Bus.Setup(value => value.PublishAsync(It.IsAny(), It.IsAny())) + .Callback((_, message) => Messages.Add(message)).Returns(Task.CompletedTask); + } + + internal string Directory { get; } + + internal NativeServiceProvider Services { get; } + + internal MSTestTestFramework Framework { get; } + + internal SessionUid Session { get; } = new("native-result-files-session"); + + internal Mock Bus { get; } = new(); + + internal List Messages { get; } = []; + + internal void SetAttachmentPaths(string first, string second) + { + string xml = new XDocument( + new XElement( + "RunSettings", + new XElement("MSTest", new XElement("DeploymentEnabled", false)), + new XElement("RunConfiguration", new XElement("DisableAppDomain", true)), + new XElement( + "TestRunParameters", + new XElement("Parameter", new XAttribute("name", "attachment"), new XAttribute("value", first)), + new XElement("Parameter", new XAttribute("name", "missing"), new XAttribute("value", second))))).ToString(); + string[]? arguments = ["native.runsettings"]; + _options.Setup(value => value.TryGetOptionArgumentList("settings", out arguments)).Returns(true); + _files.Setup(value => value.ExistFile("native.runsettings")).Returns(true); + _files.Setup(value => value.ReadAllText("native.runsettings")).Returns(xml); + } + + internal List CaptureWarnings() + { + var logger = Mock.Get(Services.Services.OfType().Single().CreateLogger("mstest-trace")); + List warnings = []; + logger.Setup(value => value.Log( + LogLevel.Warning, It.IsAny(), It.IsAny(), It.IsAny>())) + .Callback>( + (_, state, exception, formatter) => warnings.Add(formatter(state, exception))); + return warnings; + } + + internal async Task OpenAsync() + => (await Framework.CreateTestSessionAsync(new(Session, CancellationToken.None))).IsSuccess.Should().BeTrue(); + + internal async Task CloseAsync() + => (await Framework.CloseTestSessionAsync(new(Session, CancellationToken.None))).IsSuccess.Should().BeTrue(); + + internal Task RunAsync() + => Framework.ExecuteRequestAsync(new( + new RunTestExecutionRequest( + new TestSessionContext(Session), + new TestNodeUidListFilter([new TestNodeUid(typeof(AttachmentFixture).FullName + "." + nameof(AttachmentFixture.AttachesFiles))])), + Bus.Object, Mock.Of(), CancellationToken.None)); + + public void Dispose() + { + Framework.Dispose(); + MSTestInstrumentation.SetActivityFactory(null); + MSTestSettings.Reset(); + PlatformServiceProvider.Instance = _previous; + if (System.IO.Directory.Exists(Directory)) + { + System.IO.Directory.Delete(Directory, recursive: true); + } + } + } + + [TestClass] + public sealed class AttachmentFixture + { + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void AttachesFiles() + { + TestContext.AddResultFile((string)TestContext.Properties["attachment"]!); + TestContext.AddResultFile((string)TestContext.Properties["missing"]!); + } + } +}