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
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ namespace Microsoft.Testing.Platform.OutputDevice;
/// SDK the corresponding lines are swallowed exactly like the no-op device, so no unknown message id is ever
/// sent. Plain informational output (<see cref="TextOutputDeviceData"/> /
/// <see cref="FormattedTextOutputDeviceData"/>) is still discarded; only explicitly durable session messages,
/// warnings, and errors cross the wire. The
/// warnings, and errors cross the wire. Before the connection is registered, warnings and errors are written
/// to the console so the SDK can relay startup failures that occur before the handshake. The
/// <see cref="DotnetTestConnection"/> and the dotnet test execution id are resolved lazily because both become
/// available only after the output device is built (the connection is created and the execution id env var is
/// set during <c>AfterCommonServiceSetupAsync</c>).
Expand Down Expand Up @@ -98,8 +99,18 @@ private async Task ForwardAzureDevOpsAsync(AzureDevOpsCommandOutputDeviceData co

private async Task ForwardDisplayMessageAsync(byte level, string text, CancellationToken cancellationToken)
{
if (_serviceProvider.GetService<IPushOnlyProtocol>() is not DotnetTestConnection connection
|| !connection.IsDisplayMessageForwardingSupported)
if (_serviceProvider.GetService<IPushOnlyProtocol>() is not DotnetTestConnection connection)
{
if (level is DisplayMessageLevels.Error or DisplayMessageLevels.Warning)
{
// The SDK captures process output for failures that occur before the pipe handshake.
_serviceProvider.GetConsole().WriteLine(text);
}

return;
}

if (!connection.IsDisplayMessageForwardingSupported)
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ public void SetPlatformOutputDevice(Func<IServiceProvider, IPlatformOutputDevice
internal async Task<ProxyOutputDevice> BuildAsync(ServiceProvider serviceProvider, bool useServerModeOutputDevice, bool isPipeProtocol)
{
// Under the dotnet test pipe protocol, the SDK's TerminalTestReporter owns all
// user-facing output, so the host must not produce console output of its own. See #7161
// and dotnet/sdk#51615 for the broader context.
// user-facing output, so regular host output must not be written directly to the console.
// Startup diagnostics fall back to captured console output until the connection exists.
// See #7161 and dotnet/sdk#51615 for the broader context.
//
// DotnetTestPassthroughOutputDevice discards regular informational output exactly like a no-op device, but
// forwards three classes of host message to the SDK over the protocol so they are not swallowed in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ public async Task DotnetTestPipe_WhenSdkSupports130_ForwardsSessionWarningAndErr
.Distinct()];
string onlyInstanceId = Assert.ContainsSingle(forwardedInstanceIds);
Assert.AreEqual(handshakeInstanceId, onlyInstanceId);
Assert.AreEqual(string.Empty, result.TestHostResult.StandardOutput);
Assert.AreEqual(string.Empty, result.TestHostResult.StandardError);
}

[TestMethod]
Expand All @@ -104,6 +106,8 @@ public async Task DotnetTestPipe_WhenSdkOnlySupports120_DoesNotForwardDisplayMes
Assert.IsEmpty(
result.MessagesWithSerializerId(DotnetTestPipeProtocol.SerializerIds.DisplayMessage),
"No DisplayMessage should be forwarded when the negotiated protocol is below 1.3.0.");
Assert.AreEqual(string.Empty, result.TestHostResult.StandardOutput);
Assert.AreEqual(string.Empty, result.TestHostResult.StandardError);
}

public sealed class TestAssetFixture() : TestAssetFixtureBase()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests.DotnetTestPipe;

[TestClass]
public sealed class DotnetTestPipeStartupErrorTests : AcceptanceTestBase<NopAssetFixture>
{
private const string AssetName = nameof(DotnetTestPipeStartupErrorTests);

public TestContext TestContext { get; set; } = null!;

[TestMethod]
[DataRow(false, "--unknown-option", "Unknown option '--unknown-option'", DisplayName = "StartupError_UnknownOption")]
[DataRow(false, "--report-gh", "Option '--report-gh' is provided by the 'Microsoft.Testing.Extensions.GitHubActionsReport' extension. Add a package reference to use it.", DisplayName = "StartupError_MissingExtension")]
[DataRow(true, "", "Option '--my-option' is declared by multiple providers: 'ProviderA', 'ProviderB'", DisplayName = "StartupError_DuplicateProviders")]
[DataRow(false, "--config-file \"$ConfigFile$\"", "The entry 'timeout' under section 'commandLineOptions' in the testconfig.json file ('$ConfigFile$') must be either a scalar value (string, number, boolean) or an array of scalar values. Nested objects are not supported.", DisplayName = "StartupError_MalformedConfiguration")]
public async Task DotnetTest_CommandLineValidationFailure_ShowsHostDiagnostic(bool duplicateProviders, string arguments, string expectedDiagnostic)
{
using TestAsset asset = await TestAsset.GenerateAssetAsync(
AssetName,
SourceCode
.PatchTargetFrameworks(TargetFrameworks.NetCurrent)
.PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)
.PatchCodeWithReplace("$RegisterProviders$", duplicateProviders
? """
builder.CommandLine.AddProvider(() => new OptionProvider("ProviderA"));
builder.CommandLine.AddProvider(() => new OptionProvider("ProviderB"));
"""
: string.Empty));
await DotnetCli.RunAsync(
$"build \"{asset.TargetAssetPath}\" -c Release",
cancellationToken: TestContext.CancellationToken);

string configFile = Path.Combine(asset.TargetAssetPath, "invalid.testconfig.json");
arguments = arguments.Replace("$ConfigFile$", configFile, StringComparison.Ordinal);
expectedDiagnostic = expectedDiagnostic.Replace("$ConfigFile$", configFile, StringComparison.Ordinal);
var testHost = TestInfrastructure.TestHost.LocateFrom(asset.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent);

TestHostResult directResult = await testHost.ExecuteAsync(arguments, cancellationToken: TestContext.CancellationToken);
directResult.AssertExitCodeIs(ExitCode.InvalidCommandLine);
directResult.AssertOutputContains(expectedDiagnostic);

string modulePath = Path.Combine("bin", "Release", TargetFrameworks.NetCurrent, $"{AssetName}.dll");
DotnetMuxerResult result = await DotnetCli.RunAsync(
$"test --test-modules \"{modulePath}\" --root-directory \"{asset.TargetAssetPath}\" {arguments}",
workingDirectory: asset.TargetAssetPath,
failIfReturnValueIsNotZero: false,
cancellationToken: TestContext.CancellationToken);

result.AssertExitCodeIs(ExitCode.InvalidCommandLine);
result.AssertOutputContains(expectedDiagnostic);
Assert.DoesNotContain($"Usage {AssetName}", result.StandardOutput);
}

private const string SourceCode = """
#file DotnetTestPipeStartupErrorTests.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$TargetFrameworks$</TargetFrameworks>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Testing.Platform" Version="$MicrosoftTestingPlatformVersion$" />
</ItemGroup>
</Project>

#file Program.cs
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.CommandLine;
using Microsoft.Testing.Platform.Extensions.TestFramework;

ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, _) => new DummyTestFramework());
$RegisterProviders$
using ITestApplication app = await builder.BuildAsync();
return await app.RunAsync();

public sealed class OptionProvider(string uid) : ICommandLineOptionsProvider
{
public string Uid => uid;
public string Version => "1.0.0";
public string DisplayName => Uid;
public string Description => Uid;
public Task<bool> IsEnabledAsync() => Task.FromResult(true);
public IReadOnlyCollection<CommandLineOption> GetCommandLineOptions() =>
[new CommandLineOption("my-option", "Declared by two providers.", ArgumentArity.Zero, false)];
public Task<ValidationResult> ValidateOptionArgumentsAsync(CommandLineOption option, string[] arguments) =>
ValidationResult.ValidTask;
public Task<ValidationResult> ValidateCommandLineOptionsAsync(ICommandLineOptions options) =>
ValidationResult.ValidTask;
}

public sealed class DummyTestFramework : ITestFramework
{
public string Uid => nameof(DummyTestFramework);
public string Version => "1.0.0";
public string DisplayName => Uid;
public string Description => Uid;
public Task<bool> IsEnabledAsync() => Task.FromResult(true);
public Task<CreateTestSessionResult> CreateTestSessionAsync(CreateTestSessionContext context) =>
Task.FromResult(new CreateTestSessionResult { IsSuccess = true });
public Task<CloseTestSessionResult> CloseTestSessionAsync(CloseTestSessionContext context) =>
Task.FromResult(new CloseTestSessionResult { IsSuccess = true });
public Task ExecuteRequestAsync(ExecuteRequestContext context)
{
context.Complete();
return Task.CompletedTask;
}
}

#file invalid.testconfig.json
{
"commandLineOptions": {
"timeout": {}
}
}
""";
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Testing.Platform.Extensions.OutputDevice;
using Microsoft.Testing.Platform.Helpers;
using Microsoft.Testing.Platform.OutputDevice;
using Microsoft.Testing.Platform.ServerMode;
using Microsoft.Testing.Platform.Services;

using Moq;

Expand Down Expand Up @@ -50,31 +52,27 @@ public async Task DisplayAsync_WithMarkerButNoConnection_IsSwallowedWithoutThrow
}

[TestMethod]
public async Task DisplayAsync_WithWarningButNoConnection_IsSwallowedWithoutThrowing()
[DataRow(false)]
[DataRow(true)]
public async Task DisplayAsync_WithDiagnosticButNoConnection_WritesToConsole(bool isError)
{
// A warning message is recognized as forwardable (so the connection is looked up), but with no dotnet
// test connection resolved there is nothing to forward to and the message is dropped.
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(p => p.GetService(typeof(IPushOnlyProtocol))).Returns(null!);
var device = new DotnetTestPassthroughOutputDevice(serviceProvider.Object);

await device.DisplayAsync(Producer, new WarningMessageOutputDeviceData("a warning"), CancellationToken.None);

serviceProvider.Verify(p => p.GetService(typeof(IPushOnlyProtocol)), Times.Once);
}

[TestMethod]
public async Task DisplayAsync_WithErrorButNoConnection_IsSwallowedWithoutThrowing()
{
// An error message is recognized as forwardable (so the connection is looked up), but with no dotnet
// test connection resolved there is nothing to forward to and the message is dropped.
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(p => p.GetService(typeof(IPushOnlyProtocol))).Returns(null!);
var device = new DotnetTestPassthroughOutputDevice(serviceProvider.Object);

await device.DisplayAsync(Producer, new ErrorMessageOutputDeviceData("an error"), CancellationToken.None);

serviceProvider.Verify(p => p.GetService(typeof(IPushOnlyProtocol)), Times.Once);
const string message = """
Invalid command line arguments:
A diagnostic produced before the pipe connection exists.
""";
var console = new Mock<IConsole>(MockBehavior.Strict);
console.Setup(c => c.WriteLine(message));
ServiceProvider serviceProvider = new();
serviceProvider.AddService(console.Object);
var device = new DotnetTestPassthroughOutputDevice(serviceProvider);
IOutputDeviceData data = isError
? new ErrorMessageOutputDeviceData(message)
: new WarningMessageOutputDeviceData(message);

await device.DisplayAsync(Producer, data, CancellationToken.None);

console.Verify(c => c.WriteLine(message), Times.Once);
console.VerifyNoOtherCalls();
}

[TestMethod]
Expand Down
Loading