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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/Changelog-Platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)

## <a name="2.6.0" />[2.6.0] - Unreleased

### Fixed

* Preserve the invocation working directory for ordinary controller-launched test hosts so relative paths such as `--coverage-settings test.runsettings` keep working under `dotnet run`, while retaining the configured working directory for custom test host launchers.
Comment thread
Evangelink marked this conversation as resolved.
Resolved

## <a name="2.5.1" />[2.5.1] - Unreleased

## <a name="2.5.0" />[2.5.0] - 2026-10-05
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ internal sealed partial class TestHostControllersTestHost
{ $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CONTROLPIPENAME}_{currentPid}", testHostControllerCancellationServer.PipeName },
},
UseShellExecute = false,
WorkingDirectory = ServiceProvider.GetConfiguration().GetCurrentWorkingDirectory(),
// Ordinary processes inherit the controller's working directory, not the artifact directory.
WorkingDirectory = _testHostsInformation.TestHostLauncher is null
? string.Empty
: ServiceProvider.GetConfiguration().GetCurrentWorkingDirectory(),
};

List<IDataConsumer> dataConsumersBuilder = [.. _testHostsInformation.DataConsumer];
Expand Down
103 changes: 103 additions & 0 deletions test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,109 @@ public void TestMethod1()

public TestContext TestContext { get; set; }

[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task DotnetRun_WithCoverageSettings_PreservesInvocationWorkingDirectory(bool absoluteSettingsPath)
{
const string directoryTestSource = """

#file DirectoryTests.cs
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MSTestSdkTest
{
public static class StartupDirectory
{
// MSTest switches directories for test execution; capture the process startup directory first.
[ModuleInitializer]
public static void CaptureChildWorkingDirectory()
{
if (Array.IndexOf(Environment.GetCommandLineArgs(), "--internal-testhostcontroller-pid") >= 0)
{
File.WriteAllText(Environment.GetEnvironmentVariable("WORKING_DIRECTORY_MARKER")!, Environment.CurrentDirectory);
}
}
}

[TestClass]
public class DirectoryTests
{
[TestMethod]
public void ControllerChildWorkingDirectory()
{
Assert.Contains("--internal-testhostcontroller-pid", Environment.GetCommandLineArgs());
Assert.IsNull(Environment.GetEnvironmentVariable("DOTNET_CLI_TEST_COMMAND_WORKING_DIRECTORY"));
}
}
}

#file test.runsettings
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="Code Coverage">
<Configuration>
<IncludeTestAssembly>True</IncludeTestAssembly>
<CodeCoverage>
<!-- Do not rewrite the already loaded controller/test assembly during collection. -->
<EnableStaticManagedInstrumentation>False</EnableStaticManagedInstrumentation>
<EnableDynamicManagedInstrumentation>True</EnableDynamicManagedInstrumentation>
<EnableStaticNativeInstrumentation>False</EnableStaticNativeInstrumentation>
<EnableDynamicNativeInstrumentation>False</EnableDynamicNativeInstrumentation>
</CodeCoverage>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>
""";

using TestAsset testAsset = await TestAsset.GenerateAssetAsync(
AssetName,
(SingleTestSourceCode + directoryTestSource)
.PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)
.PatchCodeWithReplace("$TargetFramework$", TargetFrameworks.NetCurrent)
.PatchCodeWithReplace("$ExtraProperties$", "<EnableMicrosoftTestingExtensionsCodeCoverage>true</EnableMicrosoftTestingExtensionsCodeCoverage>"));

DotnetMuxerResult buildResult = await DotnetCli.RunAsync(
$"build \"{testAsset.TargetAssetPath}\" -c Release",
cancellationToken: TestContext.CancellationToken);
buildResult.AssertExitCodeIs(0);

string settingsPath = absoluteSettingsPath ? Path.Combine(testAsset.TargetAssetPath, "test.runsettings") : "test.runsettings";
string markerPath = Path.Combine(testAsset.TargetAssetPath, "working-directory.txt");
string resultsDirectory = Path.Combine(testAsset.TargetAssetPath, "TestResults");
DotnetMuxerResult runResult = await DotnetCli.RunAsync(
$"run --no-build -c Release -f {TargetFrameworks.NetCurrent} -- --coverage --coverage-settings \"{settingsPath}\" --coverage-output-format cobertura --coverage-output coverage.cobertura.xml --results-directory \"{resultsDirectory}\" --no-ansi --progress off",
workingDirectory: testAsset.TargetAssetPath,
environmentVariables: new()
{
["DOTNET_CLI_TEST_COMMAND_WORKING_DIRECTORY"] = null,
["WORKING_DIRECTORY_MARKER"] = markerPath,
},
cancellationToken: TestContext.CancellationToken);

runResult.AssertExitCodeIs(0);
const string expectedSummary = """
total: 2
failed: 0
succeeded: 2
skipped: 0
""";
Assert.Contains(expectedSummary.ReplaceLineEndings(), runResult.StandardOutput.ReplaceLineEndings(), runResult.ToString());
Assert.AreEqual(testAsset.TargetAssetPath, await File.ReadAllTextAsync(markerPath, TestContext.CancellationToken));

var coverage = System.Xml.Linq.XDocument.Load(Path.Combine(resultsDirectory, "coverage.cobertura.xml"));
Assert.AreEqual("coverage", coverage.Root?.Name.LocalName);
Assert.IsTrue(coverage.Descendants("class").Any(element =>
element.Attribute("name")?.Value == "MSTestSdkTest.DirectoryTests"
&& element.Descendants("line").Any(line => int.Parse(line.Attribute("hits")!.Value, CultureInfo.InvariantCulture) > 0)));
}

[TestMethod]
[DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase<NopAssetFixture>))]
public async Task RunTests_With_VSTest(string multiTfm, BuildConfiguration buildConfiguration)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public async Task CustomLauncher_IsUsedToStartTestHost_AndRunSucceeds(string cur
// Marker proves the platform delegated the launch to our ITestHostLauncher rather than
// doing the default Process.Start itself.
Assert.AreEqual("TestHostLauncher.LaunchTestHostAsync", File.ReadAllText(Path.Combine(testHost.DirectoryName, "LaunchTestHostAsync.txt")));
Assert.AreEqual(testHost.DirectoryName, File.ReadAllText(Path.Combine(testHost.DirectoryName, "WorkingDirectory.txt")));
}

public sealed class TestAssetFixture() : TestAssetFixtureBase()
Expand Down Expand Up @@ -90,6 +91,7 @@ public Task<ITestHostHandle> LaunchTestHostAsync(TestHostLaunchContext context,
// reads it from testHost.DirectoryName, which is the same folder.
string markerPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(context.FileName)!, "LaunchTestHostAsync.txt");
System.IO.File.WriteAllText(markerPath, "TestHostLauncher.LaunchTestHostAsync");
System.IO.File.WriteAllText(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(context.FileName)!, "WorkingDirectory.txt"), context.WorkingDirectory);

var startInfo = new ProcessStartInfo(context.FileName)
{
Expand Down
Loading