diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs index 4a7bb62bbc1..98a41503283 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs @@ -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 ( / /// ) 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 /// 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 AfterCommonServiceSetupAsync). @@ -98,8 +99,18 @@ private async Task ForwardAzureDevOpsAsync(AzureDevOpsCommandOutputDeviceData co private async Task ForwardDisplayMessageAsync(byte level, string text, CancellationToken cancellationToken) { - if (_serviceProvider.GetService() is not DotnetTestConnection connection - || !connection.IsDisplayMessageForwardingSupported) + if (_serviceProvider.GetService() 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; } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 965a50dda0d..27338c67c2e 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -20,8 +20,9 @@ public void SetPlatformOutputDevice(Func 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 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeDisplayMessageForwardingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeDisplayMessageForwardingTests.cs index 22282c28049..77feeed418f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeDisplayMessageForwardingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeDisplayMessageForwardingTests.cs @@ -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] @@ -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() diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeStartupErrorTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeStartupErrorTests.cs new file mode 100644 index 00000000000..96f0562d27c --- /dev/null +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeStartupErrorTests.cs @@ -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 +{ + 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 + + + $TargetFrameworks$ + Exe + enable + enable + + + + + + + #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 IsEnabledAsync() => Task.FromResult(true); + public IReadOnlyCollection GetCommandLineOptions() => + [new CommandLineOption("my-option", "Declared by two providers.", ArgumentArity.Zero, false)]; + public Task ValidateOptionArgumentsAsync(CommandLineOption option, string[] arguments) => + ValidationResult.ValidTask; + public Task 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 IsEnabledAsync() => Task.FromResult(true); + public Task CreateTestSessionAsync(CreateTestSessionContext context) => + Task.FromResult(new CreateTestSessionResult { IsSuccess = true }); + public Task 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": {} + } + } + """; +} diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/DotnetTestPassthroughOutputDeviceTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/DotnetTestPassthroughOutputDeviceTests.cs index cde751debf7..612d691c906 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/DotnetTestPassthroughOutputDeviceTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/DotnetTestPassthroughOutputDeviceTests.cs @@ -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; @@ -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(); - 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(); - 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(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]