From 2d96954460a723b6645cd9727c4424e41e61364d Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Wed, 27 Nov 2024 12:29:53 +0100 Subject: [PATCH 01/29] Only push output device messages to Test Explorer, don't push logs Logs are intended to be used for diagnosing. They shouldn't be localized and they shouldn't be pushed to Test Explorer. --- .../Hosts/ServerTestHost.cs | 9 +- .../Hosts/TestHostBuilder.cs | 13 +- .../Logging/ServerLoggerForwarder.cs | 182 ------------------ .../Logging/ServerLoggerForwarderProvider.cs | 35 ---- .../JsonRpc/ServerModePerCallOutputDevice.cs | 85 +++++++- .../Logging/ServerLoggerForwarderTests.cs | 57 ------ 6 files changed, 87 insertions(+), 294 deletions(-) delete mode 100644 src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarder.cs delete mode 100644 src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarderProvider.cs delete mode 100644 test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/ServerLoggerForwarderTests.cs diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 783713fd63c..450099f4413 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -118,13 +118,6 @@ protected override async Task InternalRunAsync() await _logger.LogDebugAsync("Starting server mode"); _messageHandler = await _messageHandlerFactory.CreateMessageHandlerAsync(_testApplicationCancellationTokenSource.CancellationToken); - // Initialize the ServerLoggerForwarderProvider, it can be null if diagnostic is disabled. - ServerLoggerForwarderProvider? serviceLoggerForwarder = ServiceProvider.GetService(); - if (serviceLoggerForwarder is not null) - { - await serviceLoggerForwarder.InitializeAsync(this); - } - await HandleMessagesAsync(); (_messageHandler as IDisposable)?.Dispose(); @@ -456,7 +449,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s requestFactory, invoker, filterFactory, - new ServerModePerCallOutputDevice(), + new ServerModePerCallOutputDevice(this, _messageMonitor), [testNodeUpdateProcessor], _testFrameworkManager, _testSessionManager, diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 674335a56c2..04097b41579 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -219,16 +219,6 @@ public async Task BuildAsync( // Get the command line options ICommandLineOptions commandLineOptions = serviceProvider.GetCommandLineOptions(); - // Register the server mode log forwarder if needed. We follow the console --diagnostic behavior. - bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); - bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); - if (hasServerFlag && isJsonRpcProtocol) - { - ServerLoggerForwarderProvider serverLoggerProxy = new(loggingState.LogLevel, serviceProvider); - serviceProvider.AddService(serverLoggerProxy); - Logging.AddProvider((logLevel, services) => serverLoggerProxy); - } - // Build the logger factory. ILoggerFactory loggerFactory = await ((LoggingManager)Logging).BuildAsync(serviceProvider, loggingState.LogLevel, systemMonitor); @@ -393,6 +383,9 @@ await LogTestHostCreatedAsync( return new TestHostOrchestratorHost(testHostOrchestratorConfiguration, serviceProvider); } + bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); + bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); + // ======= TEST HOST CONTROLLER MODE ======== // // Check if we're in the test host or we should check test controllers extensions // Environment variable check should not be needed but in case we will rollback to use only env var we will need it. diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarder.cs b/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarder.cs deleted file mode 100644 index a3a69548d22..00000000000 --- a/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarder.cs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if NETCOREAPP -using System.Diagnostics.CodeAnalysis; -using System.Threading.Channels; -#else -using System.Collections.Concurrent; -using System.Diagnostics.CodeAnalysis; -#endif -using System.Globalization; - -using Microsoft.Testing.Platform.Helpers; -using Microsoft.Testing.Platform.Hosts; -using Microsoft.Testing.Platform.Resources; - -namespace Microsoft.Testing.Platform.Logging; - -/// -/// This logger forwards the messages back to the server host so that they're -/// logged over RPC back to the client. -/// -internal sealed class ServerLoggerForwarder : ILogger, IDisposable -#if NETCOREAPP -#pragma warning disable SA1001 // Commas should be spaced correctly - , IAsyncDisposable -#pragma warning restore SA1001 // Commas should be spaced correctly -#endif -{ - private readonly LogLevel _logLevel; - private readonly IServerTestHost _serverTestHost; - private readonly Task _logLoop; -#if NETCOREAPP - private readonly Channel? _channel; -#else - private readonly BlockingCollection? _asyncLogs; -#endif - - private bool _isDisposed; - - // NOTE: We have to take the service provider because when the logger is created, the ServerTestHost is not yet registered. - public ServerLoggerForwarder(LogLevel logLevel, ITask task, IServerTestHost serverTestHost) - { - _logLevel = logLevel; - _serverTestHost = serverTestHost; -#if NETCOREAPP - _channel = Channel.CreateUnbounded(new UnboundedChannelOptions - { - // We process only 1 data at a time - SingleReader = true, - - // We don't know how many threads will call the Log method - SingleWriter = false, - - // We want to unlink the caller from the consumer - AllowSynchronousContinuations = false, - }); -#else - _asyncLogs = []; -#endif - _logLoop = task.Run(WriteLogMessageAsync, CancellationToken.None); - } - - private async Task WriteLogMessageAsync() - { -#if NETCOREAPP - // We do this check out of the try because we want to crash the process if the _channel is null. - ApplicationStateGuard.Ensure(_channel is not null); - - // We don't need cancellation token because the task will be stopped when the Channel is completed thanks to the call to Complete() inside the Dispose method. - while (await _channel.Reader.WaitToReadAsync()) - { - await PushServerLogMessageToTheMessageBusAsync(await _channel.Reader.ReadAsync()); - } -#else - ApplicationStateGuard.Ensure(_asyncLogs is not null); - - // We don't need cancellation token because the task will be stopped when the BlockingCollection is completed thanks to the call to CompleteAdding() - // inside the Dispose method. - foreach (ServerLogMessage message in _asyncLogs.GetConsumingEnumerable()) - { - await PushServerLogMessageToTheMessageBusAsync(message); - } -#endif - } - - public bool IsEnabled(LogLevel logLevel) => logLevel >= _logLevel; - - public void Log(LogLevel logLevel, TState state, Exception? exception, Func formatter) - { - if (!IsEnabled(logLevel)) - { - return; - } - - string message = formatter(state, exception); - ServerLogMessage logMessage = new(logLevel, message); - EnsureAsyncLogObjectsAreNotNull(); -#if NETCOREAPP - if (!_channel.Writer.TryWrite(logMessage)) - { - throw new InvalidOperationException("Failed to write the log to the channel"); - } -#else - _asyncLogs.Add(logMessage); -#endif - } - - public async Task LogAsync(LogLevel logLevel, TState state, Exception? exception, Func formatter) - { - if (!IsEnabled(logLevel)) - { - return; - } - - string message = formatter(state, exception); - ServerLogMessage logMessage = new(logLevel, message); - await PushServerLogMessageToTheMessageBusAsync(logMessage); - } - - private async Task PushServerLogMessageToTheMessageBusAsync(ServerLogMessage logMessage) - => await _serverTestHost.PushDataAsync(logMessage); - -#if NETCOREAPP - [MemberNotNull(nameof(_channel), nameof(_logLoop))] - private void EnsureAsyncLogObjectsAreNotNull() - { - ApplicationStateGuard.Ensure(_channel is not null); - ApplicationStateGuard.Ensure(_logLoop is not null); - } -#else - [MemberNotNull(nameof(_asyncLogs), nameof(_logLoop))] - private void EnsureAsyncLogObjectsAreNotNull() - { - ApplicationStateGuard.Ensure(_asyncLogs is not null); - ApplicationStateGuard.Ensure(_logLoop is not null); - } -#endif - - public void Dispose() - { - if (_isDisposed) - { - return; - } - - EnsureAsyncLogObjectsAreNotNull(); -#if NETCOREAPP - // Wait for all logs to be written - bool result = _channel.Writer.TryComplete(); - if (!_logLoop.Wait(TimeoutHelper.DefaultHangTimeSpanTimeout)) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.TimeoutFlushingLogsErrorMessage, TimeoutHelper.DefaultHangTimeoutSeconds)); - } -#else - // Wait for all logs to be written - _asyncLogs.CompleteAdding(); - if (!_logLoop.Wait(TimeoutHelper.DefaultHangTimeSpanTimeout)) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.TimeoutFlushingLogsErrorMessage, TimeoutHelper.DefaultHangTimeoutSeconds)); - } -#endif - _isDisposed = true; - } - -#if NETCOREAPP - public async ValueTask DisposeAsync() - { - if (_isDisposed) - { - return; - } - - EnsureAsyncLogObjectsAreNotNull(); - - // Wait for all logs to be written - _channel.Writer.TryComplete(); - await _logLoop.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); - _isDisposed = true; - } -#endif -} diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarderProvider.cs b/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarderProvider.cs deleted file mode 100644 index 8b2ffaff023..00000000000 --- a/src/Platform/Microsoft.Testing.Platform/Logging/ServerLoggerForwarderProvider.cs +++ /dev/null @@ -1,35 +0,0 @@ -// 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.Hosts; -using Microsoft.Testing.Platform.Services; - -namespace Microsoft.Testing.Platform.Logging; - -internal sealed class ServerLoggerForwarderProvider(LogLevel logLevel, IServiceProvider serviceProvider) - : ILoggerProvider -{ - private readonly LogLevel _logLevel = logLevel; - private readonly ServerLogMessageInMemoryStore _serverLogMessageInMemoryStore = new(logLevel); - - private ServerTestHost? _serverTestHost; - - // If we don't have the server test host, we just log to the in-memory store. - public ILogger CreateLogger(string categoryName) - => _serverTestHost is null - ? _serverLogMessageInMemoryStore - : new ServerLoggerForwarder(_logLevel, serviceProvider.GetTask(), _serverTestHost); - - public async Task InitializeAsync(ServerTestHost serverTestHost) - { - _serverTestHost = serverTestHost; - _serverLogMessageInMemoryStore.Initialize(serverTestHost); - - foreach (ServerLogMessage serverLogMessage in _serverLogMessageInMemoryStore) - { - await _serverTestHost.PushDataAsync(serverLogMessage); - } - - _serverLogMessageInMemoryStore.Clean(); - } -} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 46f26549e28..724c33fc7d7 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -1,14 +1,34 @@ // 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.Text; +#if NETCOREAPP +using System.Threading.Channels; +#else +using System.Collections.Concurrent; +#endif + using Microsoft.Testing.Platform.Extensions.OutputDevice; using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Hosts; +using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; namespace Microsoft.Testing.Platform.ServerMode; internal class ServerModePerCallOutputDevice : IPlatformOutputDevice { + private readonly IServerTestHost _serverTestHost; + private readonly IAsyncMonitor _asyncMonitor; + + private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + + public ServerModePerCallOutputDevice(IServerTestHost serverTestHost, IAsyncMonitor asyncMonitor) + { + _serverTestHost = serverTestHost; + _asyncMonitor = asyncMonitor; + } + public string Uid => nameof(ServerModePerCallOutputDevice); public string Version => AppVersion.DefaultSemVer; @@ -19,11 +39,72 @@ internal class ServerModePerCallOutputDevice : IPlatformOutputDevice public Task DisplayAfterSessionEndRunAsync() => Task.CompletedTask; - public Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) => Task.CompletedTask; + public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) + { + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + { + switch (data) + { + case FormattedTextOutputDeviceData formattedTextOutputDeviceData: + LogLevel logLevel = formattedTextOutputDeviceData.ForegroundColor is SystemConsoleColor color + ? color.ConsoleColor switch + { + ConsoleColor.Red => LogLevel.Error, + ConsoleColor.Yellow => LogLevel.Warning, + _ => LogLevel.Information, + } + : LogLevel.Information; + + await LogAsync(logLevel, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); + break; + + case TextOutputDeviceData textOutputDeviceData: + await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null); + break; + + case ExceptionOutputDeviceData exceptionOutputDeviceData: + await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null); + break; + } + } + } public Task DisplayBannerAsync(string? bannerMessage) => Task.CompletedTask; public Task DisplayBeforeSessionStartAsync() => Task.CompletedTask; - public Task IsEnabledAsync() => Task.FromResult(false); + public Task IsEnabledAsync() => Task.FromResult(true); + + private async Task LogAsync(LogLevel logLevel, string message, int? padding) + { + message = GetIndentedMessage(message, padding); + ServerLogMessage logMessage = new(logLevel, message); + await _serverTestHost.PushDataAsync(logMessage); + } + + private static string GetIndentedMessage(string message, int? padding) + { + int paddingValue = padding.GetValueOrDefault(); + if (paddingValue == 0) + { + return message; + } + + string indent = new(' ', paddingValue); + + if (!message.Contains('\n')) + { + return indent + message; + } + + string[] lines = message.Split(NewLineStrings, StringSplitOptions.None); + StringBuilder builder = new(); + foreach (string line in lines) + { + builder.Append(indent); + builder.AppendLine(line); + } + + return builder.ToString(); + } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/ServerLoggerForwarderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/ServerLoggerForwarderTests.cs deleted file mode 100644 index 10be06a371f..00000000000 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/ServerLoggerForwarderTests.cs +++ /dev/null @@ -1,57 +0,0 @@ -// 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.Globalization; - -using Microsoft.Testing.Platform.Extensions.Messages; -using Microsoft.Testing.Platform.Helpers; -using Microsoft.Testing.Platform.Hosts; -using Microsoft.Testing.Platform.Logging; -using Microsoft.Testing.Platform.Services; - -using Moq; - -namespace Microsoft.Testing.Platform.UnitTests; - -[TestGroup] -public class ServerLoggerForwarderTests : TestBase -{ - private const string Message = "Dummy"; - - private static readonly Func Formatter = - (state, exception) => - string.Format(CultureInfo.InvariantCulture, "{0}{1}", state, exception is not null ? $" -- {exception}" : string.Empty); - - private readonly Mock _mockServerTestHost = new(); - private readonly ServiceProvider _serviceProvider = new(); - - public ServerLoggerForwarderTests(ITestExecutionContext testExecutionContext) - : base(testExecutionContext) - { - _mockServerTestHost.Setup(x => x.PushDataAsync(It.IsAny())).Returns(Task.CompletedTask); - _serviceProvider.AddService(new SystemTask()); - _serviceProvider.AddService(_mockServerTestHost.Object); - } - - [ArgumentsProvider(nameof(LogTestHelpers.GetLogLevelCombinations), typeof(LogTestHelpers))] - public void ServerLoggerForwarder_Log(LogLevel defaultLevel, LogLevel currentLevel) - { - using (ServerLoggerForwarder serverLoggerForwarder = new(defaultLevel, new SystemTask(), _mockServerTestHost.Object)) - { - serverLoggerForwarder.Log(currentLevel, Message, null, Formatter); - } - - _mockServerTestHost.Verify(x => x.PushDataAsync(It.IsAny()), LogTestHelpers.GetExpectedLogCallTimes(defaultLevel, currentLevel)); - } - - [ArgumentsProvider(nameof(LogTestHelpers.GetLogLevelCombinations), typeof(LogTestHelpers))] - public async Task ServerLoggerForwarder_LogAsync(LogLevel defaultLevel, LogLevel currentLevel) - { - using (ServerLoggerForwarder serverLoggerForwarder = new(defaultLevel, new SystemTask(), _mockServerTestHost.Object)) - { - await serverLoggerForwarder.LogAsync(currentLevel, Message, null, Formatter); - } - - _mockServerTestHost.Verify(x => x.PushDataAsync(It.IsAny()), LogTestHelpers.GetExpectedLogCallTimes(defaultLevel, currentLevel)); - } -} From 1231ea97200c5e3532942a31d4a46bd696816dba Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 27 Nov 2024 13:02:51 +0100 Subject: [PATCH 02/29] Remove unused usings --- .../ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 724c33fc7d7..a43ecd6a0a3 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -2,11 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; -#if NETCOREAPP -using System.Threading.Channels; -#else -using System.Collections.Concurrent; -#endif using Microsoft.Testing.Platform.Extensions.OutputDevice; using Microsoft.Testing.Platform.Helpers; From a3429b03f2f6a89d4bb52079719293f9d57dc7ce Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Wed, 27 Nov 2024 15:04:54 +0100 Subject: [PATCH 03/29] Adjust test expectation for the new behavior --- .../MSTest.Acceptance.IntegrationTests/ServerModeTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index 9ca1e2813ab..4b63fa5d271 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -40,7 +40,7 @@ public async Task DiscoverAndRun(string tfm) await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); Assert.AreEqual(1, discoveryCollector.TestNodeUpdates.Count(x => x.Node.NodeType == "action"), $"Wrong number of discovery"); Assert.AreEqual(2, runCollector.TestNodeUpdates.Count, $"Wrong number of updates"); - Assert.IsFalse(logs.IsEmpty, $"Logs are empty"); + Assert.IsTrue(logs.IsEmpty, $"Logs are not empty"); Assert.IsFalse(telemetry.IsEmpty, $"telemetry is empty"); await jsonClient.Exit(); Assert.AreEqual(0, await jsonClient.WaitServerProcessExit()); From 3b0d18d221bea58770652adb80fa7927ab163605 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Thu, 28 Nov 2024 19:54:44 +0100 Subject: [PATCH 04/29] Review comments --- .../Hosts/ServerTestHost.cs | 2 +- .../JsonRpc/ServerModePerCallOutputDevice.cs | 24 +++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 450099f4413..2e1f835a036 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -449,7 +449,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s requestFactory, invoker, filterFactory, - new ServerModePerCallOutputDevice(this, _messageMonitor), + new ServerModePerCallOutputDevice(this, _messageMonitor, ServiceProvider), [testNodeUpdateProcessor], _testFrameworkManager, _testSessionManager, diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index a43ecd6a0a3..420a3ea19ae 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -8,6 +8,7 @@ using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.ServerMode; @@ -15,13 +16,15 @@ internal class ServerModePerCallOutputDevice : IPlatformOutputDevice { private readonly IServerTestHost _serverTestHost; private readonly IAsyncMonitor _asyncMonitor; + private readonly IServiceProvider _serviceProvider; private static readonly string[] NewLineStrings = { "\r\n", "\n" }; - public ServerModePerCallOutputDevice(IServerTestHost serverTestHost, IAsyncMonitor asyncMonitor) + public ServerModePerCallOutputDevice(IServerTestHost serverTestHost, IAsyncMonitor asyncMonitor, IServiceProvider serviceProvider) { _serverTestHost = serverTestHost; _asyncMonitor = asyncMonitor; + _serviceProvider = serviceProvider; } public string Uid => nameof(ServerModePerCallOutputDevice); @@ -32,7 +35,8 @@ public ServerModePerCallOutputDevice(IServerTestHost serverTestHost, IAsyncMonit public string Description => nameof(ServerModePerCallOutputDevice); - public Task DisplayAfterSessionEndRunAsync() => Task.CompletedTask; + public async Task DisplayAfterSessionEndRunAsync() + => await LogAsync(LogLevel.Trace, /*TODO: Localize*/"Finished test session", padding: null); public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { @@ -64,9 +68,21 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice } } - public Task DisplayBannerAsync(string? bannerMessage) => Task.CompletedTask; + public async Task DisplayBannerAsync(string? bannerMessage) + { + if (bannerMessage is not null) + { + await LogAsync(LogLevel.Debug, bannerMessage, padding: null); + } + } - public Task DisplayBeforeSessionStartAsync() => Task.CompletedTask; + public async Task DisplayBeforeSessionStartAsync() + { + if (_serviceProvider.GetService() is { FileLogger.FileName: { } logFileName, LogLevel: LogLevel.Trace }) + { + await LogAsync(LogLevel.Trace, $"Starting test session. Log file path is '{logFileName}'."/*TODO: Localize*/, padding: null); + } + } public Task IsEnabledAsync() => Task.FromResult(true); From 0a7df37e5d35b42ad608fe1d342b0b5d7cdb9328 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Thu, 28 Nov 2024 19:56:09 +0100 Subject: [PATCH 05/29] Cleanup possibly redundant check --- .../ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 420a3ea19ae..1f00e4508dc 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -78,7 +78,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) public async Task DisplayBeforeSessionStartAsync() { - if (_serviceProvider.GetService() is { FileLogger.FileName: { } logFileName, LogLevel: LogLevel.Trace }) + if (_serviceProvider.GetService() is { FileLogger.FileName: { } logFileName }) { await LogAsync(LogLevel.Trace, $"Starting test session. Log file path is '{logFileName}'."/*TODO: Localize*/, padding: null); } From f7d05a5cbf8cab598b8a2bec2158a054f4774345 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Thu, 28 Nov 2024 19:56:45 +0100 Subject: [PATCH 06/29] Always log something in before session --- .../ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 1f00e4508dc..458ab027027 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -82,6 +82,10 @@ public async Task DisplayBeforeSessionStartAsync() { await LogAsync(LogLevel.Trace, $"Starting test session. Log file path is '{logFileName}'."/*TODO: Localize*/, padding: null); } + else + { + await LogAsync(LogLevel.Trace, $"Starting test session."/*TODO: Localize*/, padding: null); + } } public Task IsEnabledAsync() => Task.FromResult(true); From e3299b8593b4892fbba33411f3e6a676afd45bf5 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Fri, 29 Nov 2024 14:19:53 +0100 Subject: [PATCH 07/29] Adjust --- .../Hosts/ServerTestHost.cs | 12 ++- .../Hosts/TestHostBuilder.cs | 17 ++-- .../OutputDevice/OutputDeviceManager.cs | 7 +- .../JsonRpc/ServerModePerCallOutputDevice.cs | 82 +++++++++++-------- 4 files changed, 75 insertions(+), 43 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 2e1f835a036..59b61f78e68 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -12,6 +12,7 @@ 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.ServerMode; using Microsoft.Testing.Platform.Services; @@ -443,13 +444,20 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s DateTimeOffset adapterLoadStart = _clock.UtcNow; + IPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); + // TODO: What if some one wants to have their own output device that's also compatible with server mode in IDE? + if (outputDevice is ServerModePerCallOutputDevice serverModePerCallOutputDevice) + { + await serverModePerCallOutputDevice.InitializeAsync(this); + } + // Build the per request adapter - ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new( + ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new TestFrameworkBuilderData( perRequestServiceProvider, requestFactory, invoker, filterFactory, - new ServerModePerCallOutputDevice(this, _messageMonitor, ServiceProvider), + outputDevice, [testNodeUpdateProcessor], _testFrameworkManager, _testSessionManager, diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 04097b41579..a148a7a7b2a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -196,10 +196,6 @@ public async Task BuildAsync( LoggerFactoryProxy loggerFactoryProxy = new(); serviceProvider.TryAddService(loggerFactoryProxy); - // Add output display proxy, needed by command line manager. - // We don't add to the service right now because we need special treatment between console/server mode. - IPlatformOutputDevice platformOutputDevice = ((PlatformOutputDeviceManager)OutputDisplay).Build(serviceProvider); - // Add Terminal options provider CommandLine.AddProvider(() => new TerminalTestReporterCommandLineOptionsProvider()); @@ -210,6 +206,16 @@ public async Task BuildAsync( // Set the concrete command line options to the proxy. commandLineOptionsProxy.SetCommandLineOptions(commandLineHandler); + bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); + bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); + + // TODO(youssef): In what way the output device is needed by command line manager? + // TODO(youssef): Building the platform output device depends on whether we are running server mode in TE or not. + // TODO(youssef): So we need to now create commandline handler first. :( + // Add output display proxy, needed by command line manager. + // We don't add to the service right now because we need special treatment between console/server mode. + IPlatformOutputDevice platformOutputDevice = ((PlatformOutputDeviceManager)OutputDisplay).Build(serviceProvider, hasServerFlag && isJsonRpcProtocol); + // Add FileLoggerProvider if needed if (loggingState.FileLoggerProvider is not null) { @@ -383,9 +389,6 @@ await LogTestHostCreatedAsync( return new TestHostOrchestratorHost(testHostOrchestratorConfiguration, serviceProvider); } - bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); - bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); - // ======= TEST HOST CONTROLLER MODE ======== // // Check if we're in the test host or we should check test controllers extensions // Environment variable check should not be needed but in case we will rollback to use only env var we will need it. diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 3c13dcc4a2e..30e85223cb2 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -1,6 +1,7 @@ // 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.ServerMode; using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.OutputDevice; @@ -15,7 +16,7 @@ public void SetPlatformOutputDevice(Func _messages = new(); + + private IServerTestHost? _serverTestHost; private static readonly string[] NewLineStrings = { "\r\n", "\n" }; - public ServerModePerCallOutputDevice(IServerTestHost serverTestHost, IAsyncMonitor asyncMonitor, IServiceProvider serviceProvider) + public ServerModePerCallOutputDevice(IServiceProvider serviceProvider) + => _serviceProvider = serviceProvider; + + internal async Task InitializeAsync(IServerTestHost serverTestHost) { _serverTestHost = serverTestHost; - _asyncMonitor = asyncMonitor; - _serviceProvider = serviceProvider; + + foreach (ServerLogMessage message in _messages) + { + await LogAsync(message); + } + + _messages.Clear(); } public string Uid => nameof(ServerModePerCallOutputDevice); @@ -40,31 +50,28 @@ public async Task DisplayAfterSessionEndRunAsync() public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + switch (data) { - switch (data) - { - case FormattedTextOutputDeviceData formattedTextOutputDeviceData: - LogLevel logLevel = formattedTextOutputDeviceData.ForegroundColor is SystemConsoleColor color - ? color.ConsoleColor switch - { - ConsoleColor.Red => LogLevel.Error, - ConsoleColor.Yellow => LogLevel.Warning, - _ => LogLevel.Information, - } - : LogLevel.Information; - - await LogAsync(logLevel, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); - break; - - case TextOutputDeviceData textOutputDeviceData: - await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null); - break; - - case ExceptionOutputDeviceData exceptionOutputDeviceData: - await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null); - break; - } + case FormattedTextOutputDeviceData formattedTextOutputDeviceData: + LogLevel logLevel = formattedTextOutputDeviceData.ForegroundColor is SystemConsoleColor color + ? color.ConsoleColor switch + { + ConsoleColor.Red => LogLevel.Error, + ConsoleColor.Yellow => LogLevel.Warning, + _ => LogLevel.Information, + } + : LogLevel.Information; + + await LogAsync(logLevel, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); + break; + + case TextOutputDeviceData textOutputDeviceData: + await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null); + break; + + case ExceptionOutputDeviceData exceptionOutputDeviceData: + await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null); + break; } } @@ -91,12 +98,23 @@ public async Task DisplayBeforeSessionStartAsync() public Task IsEnabledAsync() => Task.FromResult(true); private async Task LogAsync(LogLevel logLevel, string message, int? padding) + => await LogAsync(GetServerLogMessage(logLevel, message, padding)); + + private async Task LogAsync(ServerLogMessage message) { - message = GetIndentedMessage(message, padding); - ServerLogMessage logMessage = new(logLevel, message); - await _serverTestHost.PushDataAsync(logMessage); + if (_serverTestHost is null) + { + _messages.Add(message); + } + else + { + await _serverTestHost.PushDataAsync(message); + } } + private static ServerLogMessage GetServerLogMessage(LogLevel logLevel, string message, int? padding) + => new(logLevel, GetIndentedMessage(message, padding)); + private static string GetIndentedMessage(string message, int? padding) { int paddingValue = padding.GetValueOrDefault(); From 13766b5fbd074d6578ead60db5742a3b85235ca7 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Fri, 29 Nov 2024 15:56:09 +0100 Subject: [PATCH 08/29] Fix assert back and TODO --- .../OutputDevice/OutputDeviceManager.cs | 2 ++ .../MSTest.Acceptance.IntegrationTests/ServerModeTests.cs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 30e85223cb2..7dde81c10ec 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -20,6 +20,8 @@ public IPlatformOutputDevice Build(ServiceProvider serviceProvider, bool useServ { if (_platformOutputDeviceFactory is not null) { + // TODO: SetPlatformOutputDevice isn't public yet. + // Before exposing it, do we want to pass the "useServerModeOutputDevice" info to it? IPlatformOutputDevice platformOutputDevice = _platformOutputDeviceFactory(serviceProvider); return platformOutputDevice; } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index 4b63fa5d271..9ca1e2813ab 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -40,7 +40,7 @@ public async Task DiscoverAndRun(string tfm) await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); Assert.AreEqual(1, discoveryCollector.TestNodeUpdates.Count(x => x.Node.NodeType == "action"), $"Wrong number of discovery"); Assert.AreEqual(2, runCollector.TestNodeUpdates.Count, $"Wrong number of updates"); - Assert.IsTrue(logs.IsEmpty, $"Logs are not empty"); + Assert.IsFalse(logs.IsEmpty, $"Logs are empty"); Assert.IsFalse(telemetry.IsEmpty, $"telemetry is empty"); await jsonClient.Exit(); Assert.AreEqual(0, await jsonClient.WaitServerProcessExit()); From c714c07794d2d38dee0fdce41c467fd4e6556533 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Fri, 29 Nov 2024 16:53:53 +0100 Subject: [PATCH 09/29] Add test --- .../ServerMode/LogsCollector.cs | 3 +- .../ServerModeTests.cs | 2 +- ...latform.Acceptance.IntegrationTests.csproj | 6 +- .../ServerLoggingTests.cs | 171 ++++++++++++++++++ 4 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerMode/LogsCollector.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerMode/LogsCollector.cs index 037e12b643e..b4846a53703 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerMode/LogsCollector.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerMode/LogsCollector.cs @@ -7,4 +7,5 @@ namespace Microsoft.Testing.Platform.ServerMode.IntegrationTests.Messages.V100; -public class LogsCollector : ConcurrentBag; +// Not using ConcurrentBag because it's unordered. +public class LogsCollector : BlockingCollection; diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index 9ca1e2813ab..989d5feae13 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -40,7 +40,7 @@ public async Task DiscoverAndRun(string tfm) await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); Assert.AreEqual(1, discoveryCollector.TestNodeUpdates.Count(x => x.Node.NodeType == "action"), $"Wrong number of discovery"); Assert.AreEqual(2, runCollector.TestNodeUpdates.Count, $"Wrong number of updates"); - Assert.IsFalse(logs.IsEmpty, $"Logs are empty"); + Assert.IsFalse(logs.Count == 0, $"Logs are empty"); Assert.IsFalse(telemetry.IsEmpty, $"telemetry is empty"); await jsonClient.Exit(); Assert.AreEqual(0, await jsonClient.WaitServerProcessExit()); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj index 7e0e340d946..b08eb6c5d11 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj @@ -1,17 +1,21 @@ - + $(NetCurrent) $(TestRunnerAdditionalArguments) --retry-failed-tests 3 false $(DefineConstants);SKIP_INTERMEDIATE_TARGET_FRAMEWORKS + $(DefineConstants);IS_MTP Exe true + + + diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs new file mode 100644 index 00000000000..5951903b739 --- /dev/null +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -0,0 +1,171 @@ +// 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.Text.RegularExpressions; + +using Microsoft.Testing.Platform.ServerMode.IntegrationTests.Messages.V100; + +using MSTest.Acceptance.IntegrationTests.Messages.V100; + +namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; + +[TestGroup] +public sealed class ServerLoggingTests : ServerModeTestsBase +{ + private readonly TestAssetFixture _testAssetFixture; + + public ServerLoggingTests(ITestExecutionContext testExecutionContext, TestAssetFixture testAssetFixture) + : base(testExecutionContext) => _testAssetFixture = testAssetFixture; + + public async Task RunningInServerJsonRpcModeShouldHaveOutputDeviceLogsPushedToTestExplorer() + { + string tfm = TargetFrameworks.NetCurrent.Arguments; + string resultDirectory = Path.Combine(_testAssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), tfm); + var testHost = TestInfrastructure.TestHost.LocateFrom(_testAssetFixture.TargetAssetPath, "ServerLoggingTests", tfm); + using TestingPlatformClient jsonClient = await StartAsServerAndConnectToTheClientAsync(testHost); + LogsCollector logs = new(); + jsonClient.RegisterLogListener(logs); + + InitializeResponse initializeResponseArgs = await jsonClient.Initialize(); + + TestNodeUpdateCollector discoveryCollector = new(); + ResponseListener discoveryListener = await jsonClient.DiscoverTests(Guid.NewGuid(), discoveryCollector.CollectNodeUpdates); + + TestNodeUpdateCollector runCollector = new(); + ResponseListener runListener = await jsonClient.RunTests(Guid.NewGuid(), runCollector.CollectNodeUpdates); + + await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); + Assert.IsFalse(logs.Count == 0, $"Logs are empty"); + string logsString = string.Join(Environment.NewLine, logs.Select(l => l.ToString())); + string logPath = Regex.Match(logsString, "Log file path is '(.+?)'").Groups[1].Value; + + Assert.AreEqual( + $$""" + Log { LogLevel = Information, Message = Connecting to client host '127.0.0.1' port '61960' } + Log { LogLevel = Trace, Message = Starting test session. Log file path is '{{logPath}}'. } + Log { LogLevel = Error, Message = System.Exception: This is an exception output } + Log { LogLevel = Error, Message = This is a red output with padding set to 3 } + Log { LogLevel = Warning, Message = This is a yellow output with padding set to 2 } + Log { LogLevel = Information, Message = This is a blue output with padding set to 1 } + Log { LogLevel = Information, Message = This is normal text output. } + Log { LogLevel = Trace, Message = Finished test session } + Log { LogLevel = Trace, Message = Starting test session. Log file path is '{{logPath}}'. } + Log { LogLevel = Error, Message = System.Exception: This is an exception output } + Log { LogLevel = Error, Message = This is a red output with padding set to 3 } + Log { LogLevel = Warning, Message = This is a yellow output with padding set to 2 } + Log { LogLevel = Information, Message = This is a blue output with padding set to 1 } + Log { LogLevel = Information, Message = This is normal text output. } + Log { LogLevel = Trace, Message = Finished test session } + """, logsString); + } + + [TestFixture(TestFixtureSharingStrategy.PerTestGroup)] + public sealed class TestAssetFixture(AcceptanceFixture acceptanceFixture) : TestAssetFixtureBase(acceptanceFixture.NuGetGlobalPackagesFolder) + { + private const string AssetName = "TestAssetFixture"; + + public string TargetAssetPath => GetAssetPath(AssetName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (AssetName, AssetName, + Sources + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); + } + + private const string Sources = """ +#file ServerLoggingTests.csproj + + + + $TargetFrameworks$ + Exe + true + enable + preview + + + + + + + +#file Program.cs + +using System; +using System.Threading.Tasks; +using Microsoft.Testing.Platform.Builder; +using Microsoft.Testing.Platform.Capabilities.TestFramework; +using Microsoft.Testing.Platform.Extensions.Messages; +using Microsoft.Testing.Platform.Extensions.OutputDevice; +using Microsoft.Testing.Platform.Extensions.TestFramework; +using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.Services; + +public class Startup +{ + public static async Task Main(string[] args) + { + ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); + builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, serviceProvider) => new DummyTestAdapter(serviceProvider)); + using ITestApplication app = await builder.BuildAsync(); + return await app.RunAsync(); + } +} + +public class DummyTestAdapter : ITestFramework, IDataProducer, IOutputDeviceDataProducer +{ + private readonly IOutputDevice _outputDevice; + + public DummyTestAdapter(IServiceProvider serviceProvider) + { + _outputDevice = serviceProvider.GetOutputDevice(); + } + + public string Uid => nameof(DummyTestAdapter); + + public string Version => "2.0.0"; + + public string DisplayName => nameof(DummyTestAdapter); + + public string Description => nameof(DummyTestAdapter); + + public Task IsEnabledAsync() => Task.FromResult(true); + + public Type[] DataTypesProduced => new[] { typeof(TestNodeUpdateMessage) }; + + public Task CreateTestSessionAsync(CreateTestSessionContext context) + => Task.FromResult(new CreateTestSessionResult() { IsSuccess = true }); + + public Task CloseTestSessionAsync(CloseTestSessionContext context) + => Task.FromResult(new CloseTestSessionResult() { IsSuccess = true }); + + public async Task ExecuteRequestAsync(ExecuteRequestContext context) + { + await _outputDevice.DisplayAsync(this, new ExceptionOutputDeviceData(new Exception("This is an exception output"))); + await _outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData("This is a red output with padding set to 3") + { + ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Red }, + Padding = 3, + }); + + await _outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData("This is a yellow output with padding set to 2") + { + ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Yellow }, + Padding = 2, + }); + + await _outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData("This is a blue output with padding set to 1") + { + ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Blue }, + Padding = 1, + }); + + await _outputDevice.DisplayAsync(this, new TextOutputDeviceData("This is normal text output.")); + context.Complete(); + } +} +"""; + } +} From 968c79bff83188c5ffd7df8c3a500dc15e3c8302 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Fri, 29 Nov 2024 16:59:42 +0100 Subject: [PATCH 10/29] Localize --- .../Resources/PlatformResources.resx | 11 ++++++++++- .../Resources/xlf/PlatformResources.cs.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.de.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.es.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.fr.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.it.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ja.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ko.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.pl.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ru.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.tr.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.zh-Hans.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.zh-Hant.xlf | 15 +++++++++++++++ .../JsonRpc/ServerModePerCallOutputDevice.cs | 8 +++++--- 15 files changed, 210 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 5bd7f79c1a5..d37230018d6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -671,4 +671,13 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is The configuration file '{0}' specified with '--config-file' could not be found. - + + Starting test session. + + + Starting test session. The log file path is '{0}'. + + + Finished test session. + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 8db997edddc..538e514c07b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -271,6 +271,11 @@ selhalo s {0} upozorněním(i). + + Finished test session. + Finished test session. + + For test Pro testování @@ -688,6 +693,16 @@ Může mít jenom jeden argument jako řetězec ve formátu <value>[h|m|s] Spouští se server. Naslouchání na portu {0} + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Objekt pro vytváření ITestExecutionFilterFactory je už nastavený. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 154d7a643b3..63f77256122 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -271,6 +271,11 @@ fehlerhaft mit {0} Warnung(en) + + Finished test session. + Finished test session. + + For test Für Test @@ -688,6 +693,16 @@ Nimmt ein Argument als Zeichenfolge im Format <value>[h|m|s], wobei "value Server wird gestartet. An Port "{0}" lauschen + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Eine "ITestExecutionFilterFactory"-Factory ist bereits festgelegt diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index ffc6cc03283..b2416c46f3b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -271,6 +271,11 @@ error con {0} advertencias + + Finished test session. + Finished test session. + + For test Para prueba @@ -688,6 +693,16 @@ Toma un argumento como cadena con el formato <value>[h|m|s] donde 'value' Iniciando el servidor. Escuchando en el puerto '{0}' + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Ya se ha establecido una fábrica "ITestExecutionFilterFactory" diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index d312b88920f..739ec267592 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -271,6 +271,11 @@ a échoué avec {0} avertissement(s) + + Finished test session. + Finished test session. + + For test Pour le test @@ -688,6 +693,16 @@ Prend un argument sous forme de chaîne au format <value>[h|m|s] où « v Démarrage du serveur. Écoute sur le port « {0} » + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Désolé, une fabrique « ITestExecutionFilterFactory » est déjà définie diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index b87e60db7cb..e786ad7667f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -271,6 +271,11 @@ non riuscito con {0} avvisi + + Finished test session. + Finished test session. + + For test Per test @@ -688,6 +693,16 @@ Acquisisce un argomento come stringa nel formato <value>[h|m|s] dove 'valu Avvio del server. In ascolto sulla porta '{0}' + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set È già impostata una factory 'ITestExecutionFilterFactory' diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index d7e5015d90a..17887b64139 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -271,6 +271,11 @@ {0} 件の警告付きで失敗しました + + Finished test session. + Finished test session. + + For test テスト用 @@ -689,6 +694,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is サーバーを起動しています。ポート '{0}' で聞いています + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set 'ITestExecutionFilterFactory' ファクトリは既に設定されています diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 9c15b13c2d2..c0ba1b80540 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -271,6 +271,11 @@ {0} 경고와 함께 실패 + + Finished test session. + Finished test session. + + For test 테스트용 @@ -688,6 +693,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 서버를 시작하는 중입니다. 포트 '{0}'에서 수신 대기 중 + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set 'ITestExecutionFilterFactory' 팩터리가 이미 설정되어 있음 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index b8e6cb922e3..f1ad33d5f9b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -271,6 +271,11 @@ zakończono niepowodzeniem, z ostrzeżeniami w liczbie: {0} + + Finished test session. + Finished test session. + + For test Na potrzeby testu @@ -688,6 +693,16 @@ Pobiera jeden argument jako ciąg w formacie <value>[h|m|s], gdzie element Uruchamianie serwera. Nasłuchiwanie na porcie „{0}” + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Fabryka „ITestExecutionFilterFactory” jest już ustawiona diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index bcb11fe7350..14b3be41840 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -271,6 +271,11 @@ falhou com {0} aviso(s) + + Finished test session. + Finished test session. + + For test Para teste @@ -688,6 +693,16 @@ Recebe um argumento como cadeia de caracteres no formato <valor>[h|m|s] em Iniciando servidor. Escutando na porta “{0}” + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Uma fábrica “ITestExecutionFilterFactory” já está definida diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 6495697d60c..6e217bc9df2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -271,6 +271,11 @@ сбой с предупреждениями ({0}) + + Finished test session. + Finished test session. + + For test Для тестирования @@ -688,6 +693,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Выполняется запуск сервера. Прослушивание порта "{0}" + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Фабрика ITestExecutionFilterFactory уже настроена diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 207f7a4fd9a..8d9ff8f28c4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -271,6 +271,11 @@ {0} uyarıyla başarısız oldu + + Finished test session. + Finished test session. + + For test Test için @@ -688,6 +693,16 @@ Bir bağımsız değişkeni, 'value' değerinin kayan olduğu <value>[h|m| Sunucu başlatılıyor. '{0}' bağlantı noktasında dinleme işlemi yapılıyor + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set Bir 'ITestExecutionFilterFactory' fabrikası zaten ayarlanmış diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index b90e61c75d4..77401ad21bd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -271,6 +271,11 @@ 失败,出现 {0} 警告 + + Finished test session. + Finished test session. + + For test 用于测试 @@ -688,6 +693,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 正在启动服务器。正在侦听端口“{0}” + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set 已设置“ITestExecutionFilterFactory”工厂 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index b9b18bdbaa8..5212607559a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -271,6 +271,11 @@ 失敗,有 {0} 個警告 + + Finished test session. + Finished test session. + + For test 用於測試 @@ -688,6 +693,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 正在啟動伺服器。正在連接埠 '{0}' 上聆聽 + + Starting test session. + Starting test session. + + + + Starting test session. The log file path is '{0}'. + Starting test session. The log file path is '{0}'. + + An 'ITestExecutionFilterFactory' factory is already set 已設定 'ITestExecutionFilterFactory' 中心 diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 2912e72e55a..eaa6d174db6 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Concurrent; +using System.Globalization; using System.Text; using Microsoft.Testing.Platform.Extensions.OutputDevice; @@ -9,6 +10,7 @@ using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.Resources; using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.ServerMode; @@ -46,7 +48,7 @@ internal async Task InitializeAsync(IServerTestHost serverTestHost) public string Description => nameof(ServerModePerCallOutputDevice); public async Task DisplayAfterSessionEndRunAsync() - => await LogAsync(LogLevel.Trace, /*TODO: Localize*/"Finished test session", padding: null); + => await LogAsync(LogLevel.Trace, PlatformResources.FinishedTestSession, padding: null); public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { @@ -87,11 +89,11 @@ public async Task DisplayBeforeSessionStartAsync() { if (_serviceProvider.GetService() is { FileLogger.FileName: { } logFileName }) { - await LogAsync(LogLevel.Trace, $"Starting test session. Log file path is '{logFileName}'."/*TODO: Localize*/, padding: null); + await LogAsync(LogLevel.Trace, string.Format(CultureInfo.InvariantCulture, PlatformResources.StartingTestSessionWithLogFilePath, logFileName), padding: null); } else { - await LogAsync(LogLevel.Trace, $"Starting test session."/*TODO: Localize*/, padding: null); + await LogAsync(LogLevel.Trace, PlatformResources.StartingTestSession, padding: null); } } From 67673870fc911ec3e46066a0bbca881da3e00d40 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Sat, 30 Nov 2024 10:56:49 +0100 Subject: [PATCH 11/29] Fix test --- .../ServerLoggingTests.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs index 5951903b739..fc136a29584 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; [TestGroup] -public sealed class ServerLoggingTests : ServerModeTestsBase +public sealed partial class ServerLoggingTests : ServerModeTestsBase { private readonly TestAssetFixture _testAssetFixture; @@ -37,11 +37,12 @@ public async Task RunningInServerJsonRpcModeShouldHaveOutputDeviceLogsPushedToTe await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); Assert.IsFalse(logs.Count == 0, $"Logs are empty"); string logsString = string.Join(Environment.NewLine, logs.Select(l => l.ToString())); - string logPath = Regex.Match(logsString, "Log file path is '(.+?)'").Groups[1].Value; + string logPath = LogFilePathRegex().Match(logsString).Groups[1].Value; + string port = PortRegex().Match(logsString).Groups[1].Value; Assert.AreEqual( $$""" - Log { LogLevel = Information, Message = Connecting to client host '127.0.0.1' port '61960' } + Log { LogLevel = Information, Message = Connecting to client host '127.0.0.1' port '{{port}}' } Log { LogLevel = Trace, Message = Starting test session. Log file path is '{{logPath}}'. } Log { LogLevel = Error, Message = System.Exception: This is an exception output } Log { LogLevel = Error, Message = This is a red output with padding set to 3 } @@ -168,4 +169,10 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) } """; } + + [GeneratedRegex("Connecting to client host '127.0.0.1' port '(\\d+)'")] + private static partial Regex PortRegex(); + + [GeneratedRegex("The log file path is '(.+?)'")] + private static partial Regex LogFilePathRegex(); } From 74da1236746439235549e428d0798f5582f96b20 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Mon, 2 Dec 2024 15:48:17 +0100 Subject: [PATCH 12/29] Address review comment --- .../Hosts/ServerTestHost.cs | 2 +- .../OutputDevice/OutputDeviceManager.cs | 16 ++--- .../JsonRpc/ProxyPlatformOutputDevice.cs | 68 +++++++++++++++++++ .../JsonRpc/ServerModePerCallOutputDevice.cs | 2 +- 4 files changed, 76 insertions(+), 12 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 59b61f78e68..0d9315b74cb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -446,7 +446,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s IPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); // TODO: What if some one wants to have their own output device that's also compatible with server mode in IDE? - if (outputDevice is ServerModePerCallOutputDevice serverModePerCallOutputDevice) + if (outputDevice is ProxyPlatformOutputDevice { ServerModeOutputDevice: { } serverModePerCallOutputDevice }) { await serverModePerCallOutputDevice.InitializeAsync(this); } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 7dde81c10ec..5ba7b25140b 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -18,17 +18,13 @@ public void SetPlatformOutputDevice(Func nameof(ProxyPlatformOutputDevice); + + public string Version => AppVersion.DefaultSemVer; + + public string DisplayName => nameof(ProxyPlatformOutputDevice); + + public string Description => nameof(ProxyPlatformOutputDevice); + + public async Task DisplayAfterSessionEndRunAsync() + { + await _originalOutputDevice.DisplayAfterSessionEndRunAsync(); + if (ServerModeOutputDevice is not null) + { + await ServerModeOutputDevice.DisplayAfterSessionEndRunAsync(); + } + } + + public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) + { + await _originalOutputDevice.DisplayAsync(producer, data); + if (ServerModeOutputDevice is not null) + { + await ServerModeOutputDevice.DisplayAsync(producer, data); + } + } + + public async Task DisplayBannerAsync(string? bannerMessage) + { + await _originalOutputDevice.DisplayBannerAsync(bannerMessage); + if (ServerModeOutputDevice is not null) + { + await ServerModeOutputDevice.DisplayBannerAsync(bannerMessage); + } + } + + public async Task DisplayBeforeSessionStartAsync() + { + await _originalOutputDevice.DisplayBeforeSessionStartAsync(); + if (ServerModeOutputDevice is not null) + { + await ServerModeOutputDevice.DisplayBeforeSessionStartAsync(); + } + } + + public async Task IsEnabledAsync() + => (ServerModeOutputDevice is not null && await ServerModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); +} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index eaa6d174db6..d73d7e45629 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -15,7 +15,7 @@ namespace Microsoft.Testing.Platform.ServerMode; -internal class ServerModePerCallOutputDevice : IPlatformOutputDevice +internal sealed class ServerModePerCallOutputDevice : IPlatformOutputDevice { private readonly IServiceProvider _serviceProvider; private readonly ConcurrentBag _messages = new(); From 5560e40588950ebd84231b6d0564e4e2c6afa52a Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Mon, 2 Dec 2024 16:05:12 +0100 Subject: [PATCH 13/29] Refactor --- .../Hosts/ServerTestHost.cs | 4 +-- .../OutputDevice/OutputDeviceManager.cs | 2 +- .../JsonRpc/ProxyPlatformOutputDevice.cs | 33 ++++++++++++------- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 0d9315b74cb..3303ac3a5d2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -446,9 +446,9 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s IPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); // TODO: What if some one wants to have their own output device that's also compatible with server mode in IDE? - if (outputDevice is ProxyPlatformOutputDevice { ServerModeOutputDevice: { } serverModePerCallOutputDevice }) + if (outputDevice is ProxyPlatformOutputDevice proxyPlatformOutputDevice) { - await serverModePerCallOutputDevice.InitializeAsync(this); + await proxyPlatformOutputDevice.InitializeAsync(this); } // Build the per request adapter diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 5ba7b25140b..7a43ce73b4a 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -16,7 +16,7 @@ public void SetPlatformOutputDevice(Func nameof(ProxyPlatformOutputDevice); public string Version => AppVersion.DefaultSemVer; @@ -30,39 +31,47 @@ public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, Ser public async Task DisplayAfterSessionEndRunAsync() { await _originalOutputDevice.DisplayAfterSessionEndRunAsync(); - if (ServerModeOutputDevice is not null) + if (_serverModeOutputDevice is not null) { - await ServerModeOutputDevice.DisplayAfterSessionEndRunAsync(); + await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); } } public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { await _originalOutputDevice.DisplayAsync(producer, data); - if (ServerModeOutputDevice is not null) + if (_serverModeOutputDevice is not null) { - await ServerModeOutputDevice.DisplayAsync(producer, data); + await _serverModeOutputDevice.DisplayAsync(producer, data); } } public async Task DisplayBannerAsync(string? bannerMessage) { await _originalOutputDevice.DisplayBannerAsync(bannerMessage); - if (ServerModeOutputDevice is not null) + if (_serverModeOutputDevice is not null) { - await ServerModeOutputDevice.DisplayBannerAsync(bannerMessage); + await _serverModeOutputDevice.DisplayBannerAsync(bannerMessage); } } public async Task DisplayBeforeSessionStartAsync() { await _originalOutputDevice.DisplayBeforeSessionStartAsync(); - if (ServerModeOutputDevice is not null) + if (_serverModeOutputDevice is not null) { - await ServerModeOutputDevice.DisplayBeforeSessionStartAsync(); + await _serverModeOutputDevice.DisplayBeforeSessionStartAsync(); } } public async Task IsEnabledAsync() - => (ServerModeOutputDevice is not null && await ServerModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); + => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); + + internal async Task InitializeAsync(ServerTestHost serverTestHost) + { + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.InitializeAsync(serverTestHost); + } + } } From 7874d42479be7caa31317387e213c78a6fd75228 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Mon, 2 Dec 2024 16:09:20 +0100 Subject: [PATCH 14/29] Further cleanup --- .../Microsoft.Testing.Platform/Hosts/ServerTestHost.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 3303ac3a5d2..70c230ff6da 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -444,12 +444,8 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s DateTimeOffset adapterLoadStart = _clock.UtcNow; - IPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); - // TODO: What if some one wants to have their own output device that's also compatible with server mode in IDE? - if (outputDevice is ProxyPlatformOutputDevice proxyPlatformOutputDevice) - { - await proxyPlatformOutputDevice.InitializeAsync(this); - } + ProxyPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); + await outputDevice.InitializeAsync(this); // Build the per request adapter ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new TestFrameworkBuilderData( From a823ac033f59281eca2a91225d180d85e49920e3 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Mon, 2 Dec 2024 16:17:21 +0100 Subject: [PATCH 15/29] Fix build errors --- src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs | 1 - .../ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 70c230ff6da..0a8b8336b46 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -12,7 +12,6 @@ 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.ServerMode; using Microsoft.Testing.Platform.Services; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs index 1d3657d739e..8cbb0d0bfba 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs @@ -1,7 +1,6 @@ // 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.Extensions.OutputDevice; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Hosts; From f6d0c1be180b4df60ba533e5592daeb0638700b8 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Mon, 2 Dec 2024 16:41:57 +0100 Subject: [PATCH 16/29] Fix missing initialization --- .../ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs index 8cbb0d0bfba..738a186c5e8 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs @@ -1,6 +1,7 @@ // 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.Extensions; using Microsoft.Testing.Platform.Extensions.OutputDevice; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Hosts; @@ -8,7 +9,7 @@ namespace Microsoft.Testing.Platform.ServerMode; -internal sealed class ProxyPlatformOutputDevice : IPlatformOutputDevice +internal sealed class ProxyPlatformOutputDevice : IPlatformOutputDevice, IAsyncInitializableExtension { private readonly IPlatformOutputDevice _originalOutputDevice; private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; @@ -63,6 +64,9 @@ public async Task DisplayBeforeSessionStartAsync() } } + public async Task InitializeAsync() + => await _originalOutputDevice.TryInitializeAsync(); + public async Task IsEnabledAsync() => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); From edf7751007f8cc3954553d28c30374d4c6b33bd4 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 07:47:36 +0100 Subject: [PATCH 17/29] Follow-up per recent changes --- .../JsonRpc/ServerModePerCallOutputDevice.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index d73d7e45629..10a040094c5 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -10,6 +10,7 @@ using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.OutputDevice.Terminal; using Microsoft.Testing.Platform.Resources; using Microsoft.Testing.Platform.Services; @@ -55,22 +56,21 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice switch (data) { case FormattedTextOutputDeviceData formattedTextOutputDeviceData: - LogLevel logLevel = formattedTextOutputDeviceData.ForegroundColor is SystemConsoleColor color - ? color.ConsoleColor switch - { - ConsoleColor.Red => LogLevel.Error, - ConsoleColor.Yellow => LogLevel.Warning, - _ => LogLevel.Information, - } - : LogLevel.Information; - - await LogAsync(logLevel, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); + await LogAsync(LogLevel.Information, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); break; case TextOutputDeviceData textOutputDeviceData: await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null); break; + case WarningMessageOutputDeviceData warningData: + await LogAsync(LogLevel.Warning, warningData.Message, padding: null); + break; + + case ErrorMessageOutputDeviceData errorData: + await LogAsync(LogLevel.Error, errorData.Message, padding: null); + break; + case ExceptionOutputDeviceData exceptionOutputDeviceData: await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null); break; From b4bf543b2c8d038e3e7ac50d1d49b48f5a198d34 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 07:47:58 +0100 Subject: [PATCH 18/29] Remove unused using --- .../ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 10a040094c5..176a37a3e9e 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -10,7 +10,6 @@ using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; -using Microsoft.Testing.Platform.OutputDevice.Terminal; using Microsoft.Testing.Platform.Resources; using Microsoft.Testing.Platform.Services; From 1d355c2798b7b02a38bbfaea08faa26727199c32 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 07:59:27 +0100 Subject: [PATCH 19/29] Temporary restore `FormattedTextOutputDeviceDataBuilder` --- .../FormattedTextOutputDeviceDataBuilder.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs new file mode 100644 index 00000000000..59a18ef1ac0 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs @@ -0,0 +1,20 @@ +// 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.ComponentModel; + +namespace Microsoft.Testing.Platform.OutputDevice; + +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("Do not use this class. This is present temporarily for internal usages and will be removed after fixing the internal usages", error: true)] +internal static class FormattedTextOutputDeviceDataBuilder +{ + public static IOutputDeviceData CreateGreenConsoleColorText(string text) + => new TextOutputDeviceData(text); + + public static IOutputDeviceData CreateRedConsoleColorText(string text) + => new ErrorMessageOutputDeviceData(text); + + public static IOutputDeviceData CreateYellowConsoleColorText(string text) + => new WarningMessageOutputDeviceData(text); +} From 25dbaaf0d3edfece2bc1f9160a3e690c6b6843a5 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 08:17:31 +0100 Subject: [PATCH 20/29] Adjust --- .../FormattedTextOutputDeviceDataBuilder.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs index 59a18ef1ac0..0741b46c0de 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/FormattedTextOutputDeviceDataBuilder.cs @@ -6,15 +6,15 @@ namespace Microsoft.Testing.Platform.OutputDevice; [EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("Do not use this class. This is present temporarily for internal usages and will be removed after fixing the internal usages", error: true)] +[Obsolete("Do not use this class. This is present temporarily for internal usages (in Retry extension) and will be removed after fixing the internal usages", error: true)] internal static class FormattedTextOutputDeviceDataBuilder { - public static IOutputDeviceData CreateGreenConsoleColorText(string text) - => new TextOutputDeviceData(text); + public static FormattedTextOutputDeviceData CreateGreenConsoleColorText(string text) + => new(text) { ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Green } }; - public static IOutputDeviceData CreateRedConsoleColorText(string text) - => new ErrorMessageOutputDeviceData(text); + public static FormattedTextOutputDeviceData CreateRedConsoleColorText(string text) + => new(text) { ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Red } }; - public static IOutputDeviceData CreateYellowConsoleColorText(string text) - => new WarningMessageOutputDeviceData(text); + public static FormattedTextOutputDeviceData CreateYellowConsoleColorText(string text) + => new(text) { ForegroundColor = new SystemConsoleColor() { ConsoleColor = ConsoleColor.Yellow } }; } From adb40be6c3d9881689ab7890d162c8790baf7002 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 09:14:44 +0100 Subject: [PATCH 21/29] Progress --- .../OutputDevice/TerminalOutputDevice.cs | 1 + .../JsonRpc/ProxyPlatformOutputDevice.cs | 58 ++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 05b5a39fc33..76bf420b5f3 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -25,6 +25,7 @@ namespace Microsoft.Testing.Platform.OutputDevice; /// /// Implementation of output device that writes to terminal with progress and optionally with ANSI. /// +// NOTE: !!! Any interfaces here will likely need to be implemented by ProxyPlatformOutputDevice as well. !!! internal partial class TerminalOutputDevice : IHotReloadPlatformOutputDevice, IDataConsumer, IOutputDeviceDataProducer, diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs index 738a186c5e8..765899e4f1f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs @@ -2,14 +2,25 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.Extensions; +using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.OutputDevice; +using Microsoft.Testing.Platform.Extensions.TestHost; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.TestHost; namespace Microsoft.Testing.Platform.ServerMode; -internal sealed class ProxyPlatformOutputDevice : IPlatformOutputDevice, IAsyncInitializableExtension +// Any interfaces that can have special treatment for any output device should be implemented by +// this proxy class and be forwarded properly. +// This is not so good. How can we make sure we are not missing any interfaces that may be implemented by external output devices? +internal sealed class ProxyPlatformOutputDevice : IHotReloadPlatformOutputDevice, + IDataConsumer, + IOutputDeviceDataProducer, + ITestSessionLifetimeHandler, + IDisposable, + IAsyncInitializableExtension { private readonly IPlatformOutputDevice _originalOutputDevice; private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; @@ -28,6 +39,24 @@ public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, Ser public string Description => nameof(ProxyPlatformOutputDevice); + public Type[] DataTypesConsumed => (_originalOutputDevice as IDataConsumer)?.DataTypesConsumed ?? Array.Empty(); + + public async Task DisplayBeforeHotReloadSessionStartAsync() + { + if (_originalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) + { + await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync(); + } + } + + public async Task DisplayAfterHotReloadSessionEndAsync() + { + if (_originalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) + { + await hotReloadOutputDevice.DisplayAfterHotReloadSessionEndAsync(); + } + } + public async Task DisplayAfterSessionEndRunAsync() { await _originalOutputDevice.DisplayAfterSessionEndRunAsync(); @@ -70,6 +99,22 @@ public async Task InitializeAsync() public async Task IsEnabledAsync() => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); + public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, CancellationToken cancellationToken) + { + if (_originalOutputDevice is ITestSessionLifetimeHandler originalLifetimeHandler) + { + await originalLifetimeHandler.OnTestSessionFinishingAsync(sessionUid, cancellationToken); + } + } + + public async Task OnTestSessionStartingAsync(SessionUid sessionUid, CancellationToken cancellationToken) + { + if (_originalOutputDevice is ITestSessionLifetimeHandler originalLifetimeHandler) + { + await originalLifetimeHandler.OnTestSessionStartingAsync(sessionUid, cancellationToken); + } + } + internal async Task InitializeAsync(ServerTestHost serverTestHost) { if (_serverModeOutputDevice is not null) @@ -77,4 +122,15 @@ internal async Task InitializeAsync(ServerTestHost serverTestHost) await _serverModeOutputDevice.InitializeAsync(serverTestHost); } } + + public async Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken) + { + if (_originalOutputDevice is IDataConsumer dataConsumer) + { + await dataConsumer.ConsumeAsync(dataProducer, value, cancellationToken); + } + } + + public void Dispose() + => (_originalOutputDevice as IDisposable)?.Dispose(); } From 074227f7960a604362ef70b0d95654d784fc3ccb Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 09:58:09 +0100 Subject: [PATCH 22/29] Forward some messages to output device (hence, to TE) --- .../Hosts/ServerTestHost.cs | 44 +++++++++++++++++-- .../Resources/PlatformResources.resx | 10 +++++ .../Resources/xlf/PlatformResources.cs.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.de.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.es.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.fr.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.it.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.ja.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.ko.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.pl.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.ru.xlf | 15 +++++++ .../Resources/xlf/PlatformResources.tr.xlf | 15 +++++++ .../xlf/PlatformResources.zh-Hans.xlf | 15 +++++++ .../xlf/PlatformResources.zh-Hant.xlf | 15 +++++++ 15 files changed, 245 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 06fb2466d8d..bec826c83fb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -8,11 +8,14 @@ using Microsoft.Testing.Internal.Framework; using Microsoft.Testing.Platform.Capabilities.TestFramework; 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.Resources; using Microsoft.Testing.Platform.ServerMode; using Microsoft.Testing.Platform.Services; using Microsoft.Testing.Platform.Telemetry; @@ -20,7 +23,7 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed partial class ServerTestHost : CommonTestHost, IServerTestHost, IDisposable +internal sealed partial class ServerTestHost : CommonTestHost, IServerTestHost, IDisposable, IOutputDeviceDataProducer { public const string ProtocolVersion = "1.0.0"; private readonly Func> _buildTestFrameworkAsync; @@ -93,13 +96,38 @@ public ServerTestHost( protected override bool RunTestApplicationLifeCycleCallbacks => true; - private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) - => _logger.LogWarning($"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}"); + public string Uid => nameof(ServerTestHost); - private void OnTaskSchedulerUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) + public string Version => AppVersion.DefaultSemVer; + + public string DisplayName => PlatformResources.ServerTestHostDisplayName; + + public string Description => PlatformResources.ServerTestHostDescription; + +#pragma warning disable VSTHRD100 // Avoid async void methods + private async void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods + { + _logger.LogWarning($"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}"); + + // Looks like nothing in this message to really be localized? + // All are class names, method names, property names, and placeholders. So none is localizable? + await ServiceProvider.GetOutputDevice().DisplayAsync( + this, + new WarningMessageOutputDeviceData( + $"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}")); + } + +#pragma warning disable VSTHRD100 // Avoid async void methods + private async void OnTaskSchedulerUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods { e.SetObserved(); _logger.LogWarning($"[ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {e.Exception}"); + + // Looks like nothing in this message to really be localized? + // All are class names, method names, property names, and placeholders. So none is localizable? + await ServiceProvider.GetOutputDevice().DisplayAsync(this, new WarningMessageOutputDeviceData(PlatformResources.UnobservedTaskExceptionWarningMessage)); } [MemberNotNull(nameof(_messageHandler))] @@ -262,6 +290,12 @@ private async Task HandleNotificationAsync(NotificationMessage message, Cancella if (cancellationException is null) { await _logger.LogWarningAsync($"Exception during the cancellation of request id '{args.CancelRequestId}'"); + + // TODO: Localize + await ServiceProvider.GetOutputDevice().DisplayAsync( + this, + new WarningMessageOutputDeviceData( + $"Exception during the cancellation of request id '{args.CancelRequestId}'")); } } @@ -696,6 +730,8 @@ await SendMessageAsync( } } + public Task IsEnabledAsync() => throw new NotImplementedException(); + private sealed class RpcInvocationState : IDisposable { private readonly Lock _cancellationTokenSourceLock = new(); diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index d37230018d6..2e83f07dcb0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -680,4 +680,14 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Finished test session. + + Server mode test host + + + The 'ITestHost' implementation used when running server mode. + + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index fb7d3d2bf55..f0509501c1c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -638,6 +638,16 @@ Může mít jenom jeden argument jako řetězec ve formátu <value>[h|m|s] Objekt pro vytváření filtru provádění testů serveru + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Nelze najít službu typu {0}. @@ -912,6 +922,11 @@ Platné hodnoty jsou Normal a Detailed. Výchozí hodnota je Normal. Komunikační protokol {0} není podporován. + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Toto umístění programu se považuje za nedostupné. File={0}, Line={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 63f77256122..5bc30251c71 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -638,6 +638,16 @@ Nimmt ein Argument als Zeichenfolge im Format <value>[h|m|s], wobei "value Ausführungsfilterfactory des Servertests + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Der Dienst vom Typ "{0}" wurde nicht gefunden. @@ -912,6 +922,11 @@ Gültige Werte sind „Normal“, „Detailed“. Der Standardwert ist „Normal Das Kommunikationsprotokoll "{0}" wird nicht unterstützt + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Dieser Programmspeicherort wird als nicht erreichbar betrachtet. File='{0}' Line={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index b2416c46f3b..a39e942c098 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -638,6 +638,16 @@ Toma un argumento como cadena con el formato <value>[h|m|s] donde 'value' Fábrica de filtros de ejecución de pruebas de servidor + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' No se encuentra el servicio de tipo '{0}' @@ -912,6 +922,11 @@ Los valores válidos son 'Normal', 'Detallado'. El valor predeterminado es 'Norm No se admite el protocolo de comunicación '{0}' + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Se considera que esta ubicación del programa es inaccesible. Archivo=''{0}'' Línea={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 87f2eca4d32..374079d0464 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -638,6 +638,16 @@ Prend un argument sous forme de chaîne au format <value>[h|m|s] où « v Fabrique de filtres d’exécution de tests du serveur + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Service de type « {0} » introuvable @@ -912,6 +922,11 @@ Les valeurs valides sont « Normal » et « Détaillé ». La valeur par dé Le protocole de communication « {0} » n’est pas pris en charge + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Cet emplacement du programme est considéré comme inaccessible. File=« {0} », Ligne={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index 49013f144b8..52c39cb9ba2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -638,6 +638,16 @@ Acquisisce un argomento come stringa nel formato <value>[h|m|s] dove 'valu Factory del filtro per l'esecuzione dei test del server + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Impossibile trovare il servizio di tipo '{0}' @@ -912,6 +922,11 @@ I valori validi sono 'Normal', 'Detailed'. L'impostazione predefinita è 'Normal Il protocollo di comunicazione '{0}' non è supportato + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} La posizione del programma è ritenuta non raggiungibile. File='{0}', Riga={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 7cd6a6a66ee..69393fd613e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -639,6 +639,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is サーバー テスト実行フィルター ファクトリ + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' '{0}' 型のサービスが見つかりません @@ -913,6 +923,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 通信プロトコル '{0}' はサポートされていません + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} このプログラムの場所に到達できないと考えられます。ファイル='{0}'、行={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index c0ba1b80540..bd0c61bb7ee 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -638,6 +638,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 서버 테스트 실행 필터 팩터리 + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' '{0}' 형식의 서비스를 찾을 수 없습니다. @@ -912,6 +922,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 통신 프로토콜 '{0}'은(는) 지원되지 않습니다. + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} 이 프로그램 위치에 연결할 수 없는 것으로 생각됩니다. File='{0}' Line={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index f1ad33d5f9b..d1e0325506a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -638,6 +638,16 @@ Pobiera jeden argument jako ciąg w formacie <value>[h|m|s], gdzie element Fabryka filtrów wykonywania testów serwera + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Nie można odnaleźć usługi typu „{0}” @@ -912,6 +922,11 @@ Prawidłowe wartości to „Normalne”, „Szczegółowe”. Wartość domyśln Protokół komunikacyjny „{0}” nie jest obsługiwany + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Ta lokalizacja programu jest uważana za nieosiągalną. Plik=„{0}”, Wiersz={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 4a88e4c4642..16761f8a18c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -638,6 +638,16 @@ Recebe um argumento como cadeia de caracteres no formato <valor>[h|m|s] em Fábrica de filtros de execução de teste de servidor + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Não é possível localizar o serviço do tipo "{0}" @@ -912,6 +922,11 @@ Os valores válidos são “Normal”, “Detalhado”. O padrão é “Normal O protocolo de comunicação “{0}” não tem suporte + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Este local do programa é considerado inacessível. Arquivo='{0}' Linha={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index fa0b4b2829b..598c726e44e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -638,6 +638,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Фабрика фильтров выполнения тестов сервера + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' Не удалось найти службу типа "{0}" @@ -912,6 +922,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. Протокол коммуникации "{0}" не поддерживается + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Похоже, что это расположение программы является недоступным. Файл="{0}", строка={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 933b40fe7e9..e6de38c0c63 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -638,6 +638,16 @@ Bir bağımsız değişkeni, 'value' değerinin kayan olduğu <value>[h|m| Sunucu test yürütme filtresi fabrikası + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' '{0}' türündeki hizmet bulunamıyor @@ -912,6 +922,11 @@ Geçerli değerler: ‘Normal’, ‘Ayrıntılı’. Varsayılan değer: ‘Nor '{0}' iletişim protokolü desteklenmiyor + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} Bu program konumu erişilemez olarak görülüyor. Dosya='{0}', Satır={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 3e414aa6b2d..69a3b6048d4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -638,6 +638,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 服务器测试执行筛选工厂 + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' 找不到“{0}”类型的服务 @@ -912,6 +922,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 不支持通信协议“{0}” + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} 此程序位置被视为无法访问。文件='{0}',行={1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 5212607559a..d414fb2731a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -638,6 +638,16 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 伺服器測試執行篩選條件中心 + + The 'ITestHost' implementation used when running server mode. + The 'ITestHost' implementation used when running server mode. + + + + Server mode test host + Server mode test host + + Cannot find service of type '{0}' 找不到類型 '{0}' 的服務 @@ -912,6 +922,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 通訊協定 '{0}' 不受支援 + + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} + {0} is the exception that was unhandled/unobserved + This program location is thought to be unreachable. File='{0}' Line={1} 此程式位置被認為無法連線。File='{0}' Line={1} From 870fb58558b66e92c7b87f13205dd493bc00dc34 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 12:36:05 +0100 Subject: [PATCH 23/29] Cleanup --- .../Hosts/CommonTestHost.cs | 10 +-- .../Hosts/TestFrameworkBuilderData.cs | 2 + .../Hosts/TestHostBuilder.cs | 19 ++---- .../OutputDevice/OutputDeviceManager.cs | 8 ++- .../ProxyPlatformOutputDevice.cs | 64 ++++--------------- .../Services/ServiceProviderExtensions.cs | 4 +- 6 files changed, 34 insertions(+), 73 deletions(-) rename src/Platform/Microsoft.Testing.Platform/{ServerMode/JsonRpc => OutputDevice}/ProxyPlatformOutputDevice.cs (55%) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 15ea8f2ccd1..71ef8d5bc56 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -119,7 +119,7 @@ private async Task RunTestAppAsync(CancellationToken testApplicationCancell protected abstract Task InternalRunAsync(); - protected static async Task ExecuteRequestAsync(IPlatformOutputDevice outputDevice, ITestSessionContext testSessionInfo, + protected static async Task ExecuteRequestAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext testSessionInfo, ServiceProvider serviceProvider, BaseMessageBus baseMessageBus, ITestFramework testFramework, TestHost.ClientInfo client) { CancellationToken testSessionCancellationToken = serviceProvider.GetTestSessionContext().CancellationToken; @@ -142,12 +142,12 @@ protected static async Task ExecuteRequestAsync(IPlatformOutputDevice outputDevi await DisplayAfterSessionEndRunAsync(outputDevice, testSessionInfo, testSessionCancellationToken); } - private static async Task DisplayBeforeSessionStartAsync(IPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) + private static async Task DisplayBeforeSessionStartAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display before session start await outputDevice.DisplayBeforeSessionStartAsync(); - if (outputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandler) + if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandler) { await testSessionLifetimeHandler.OnTestSessionStartingAsync( sessionInfo.SessionId, @@ -155,13 +155,13 @@ await testSessionLifetimeHandler.OnTestSessionStartingAsync( } } - private static async Task DisplayAfterSessionEndRunAsync(IPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) + private static async Task DisplayAfterSessionEndRunAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display after session end await outputDevice.DisplayAfterSessionEndRunAsync(); // We want to ensure that the output service is the last one to run - if (outputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandlerFinishing) + if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandlerFinishing) { await testSessionLifetimeHandlerFinishing.OnTestSessionFinishingAsync( sessionInfo.SessionId, diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs index 838dc78ef3f..bdc541505df 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs @@ -28,6 +28,8 @@ internal class TestFrameworkBuilderData(ServiceProvider serviceProvider, ITestEx public IPlatformOutputDevice PlatformOutputDisplayService { get; } = platformOutputDisplayService; + internal IPlatformOutputDevice OriginalPlatformOutputDisplayService => ((ProxyPlatformOutputDevice)PlatformOutputDisplayService).OriginalOutputDevice; + public IEnumerable ServerPerCallConsumers { get; } = serverPerCallConsumers; public TestFrameworkManager TestFrameworkManager { get; } = testFrameworkManager; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 1903dc818c7..dd83b3d50ac 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -209,12 +209,7 @@ public async Task BuildAsync( bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); - // TODO(youssef): In what way the output device is needed by command line manager? - // TODO(youssef): Building the platform output device depends on whether we are running server mode in TE or not. - // TODO(youssef): So we need to now create commandline handler first. :( - // Add output display proxy, needed by command line manager. - // We don't add to the service right now because we need special treatment between console/server mode. - IPlatformOutputDevice platformOutputDevice = ((PlatformOutputDeviceManager)OutputDisplay).Build(serviceProvider, hasServerFlag && isJsonRpcProtocol); + ProxyPlatformOutputDevice platformOutputDevice = await ((PlatformOutputDeviceManager)OutputDisplay).BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol); // Add FileLoggerProvider if needed if (loggingState.FileLoggerProvider is not null) @@ -232,15 +227,9 @@ public async Task BuildAsync( loggerFactoryProxy.SetLoggerFactory(loggerFactory); // Initialize the output device if needed. - if (await platformOutputDevice.IsEnabledAsync()) + if (await platformOutputDevice.OriginalOutputDevice.IsEnabledAsync()) { - await platformOutputDevice.TryInitializeAsync(); - } - else - { - // If for some reason the custom output is not enabled we opt-in the default terminal output device. - platformOutputDevice = PlatformOutputDeviceManager.GetDefaultTerminalOutputDevice(serviceProvider); - await platformOutputDevice.TryInitializeAsync(); + await platformOutputDevice.OriginalOutputDevice.TryInitializeAsync(); } // Add the platform output device to the service provider for both modes. @@ -654,7 +643,7 @@ private async Task BuildTestFrameworkAsync(TestFrameworkBuilderD // creations and we could lose interesting diagnostic information. List dataConsumersBuilder = []; - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.PlatformOutputDisplayService, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.OriginalPlatformOutputDisplayService, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestFactory, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestInvoker, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionFilterFactory, serviceProvider, dataConsumersBuilder); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 7a43ce73b4a..de83e7543ff 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -16,7 +16,7 @@ public void SetPlatformOutputDevice(Func BuildAsync(ServiceProvider serviceProvider, bool useServerModeOutputDevice) { // TODO: SetPlatformOutputDevice isn't public yet. // Before exposing it, do we want to pass the "useServerModeOutputDevice" info to it? @@ -24,6 +24,12 @@ internal ProxyPlatformOutputDevice Build(ServiceProvider serviceProvider, bool u ? GetDefaultTerminalOutputDevice(serviceProvider) : _platformOutputDeviceFactory(serviceProvider); + // If the externally provided output device is not enabled, we opt-in the default terminal output device. + if (_platformOutputDeviceFactory is not null && !await nonServerOutputDevice.IsEnabledAsync()) + { + nonServerOutputDevice = GetDefaultTerminalOutputDevice(serviceProvider); + } + return new ProxyPlatformOutputDevice(nonServerOutputDevice, useServerModeOutputDevice ? new ServerModePerCallOutputDevice(serviceProvider) : null); } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs similarity index 55% rename from src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs rename to src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs index 765899e4f1f..370db7ca795 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs @@ -2,35 +2,28 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.Extensions; -using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.OutputDevice; -using Microsoft.Testing.Platform.Extensions.TestHost; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Hosts; -using Microsoft.Testing.Platform.OutputDevice; -using Microsoft.Testing.Platform.TestHost; +using Microsoft.Testing.Platform.ServerMode; -namespace Microsoft.Testing.Platform.ServerMode; +namespace Microsoft.Testing.Platform.OutputDevice; // Any interfaces that can have special treatment for any output device should be implemented by // this proxy class and be forwarded properly. // This is not so good. How can we make sure we are not missing any interfaces that may be implemented by external output devices? -internal sealed class ProxyPlatformOutputDevice : IHotReloadPlatformOutputDevice, - IDataConsumer, - IOutputDeviceDataProducer, - ITestSessionLifetimeHandler, - IDisposable, - IAsyncInitializableExtension +internal sealed class ProxyPlatformOutputDevice : IHotReloadPlatformOutputDevice, IDisposable { - private readonly IPlatformOutputDevice _originalOutputDevice; private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, ServerModePerCallOutputDevice? serverModeOutputDevice) { - _originalOutputDevice = originalOutputDevice; + OriginalOutputDevice = originalOutputDevice; _serverModeOutputDevice = serverModeOutputDevice; } + internal IPlatformOutputDevice OriginalOutputDevice { get; } + public string Uid => nameof(ProxyPlatformOutputDevice); public string Version => AppVersion.DefaultSemVer; @@ -39,11 +32,9 @@ public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, Ser public string Description => nameof(ProxyPlatformOutputDevice); - public Type[] DataTypesConsumed => (_originalOutputDevice as IDataConsumer)?.DataTypesConsumed ?? Array.Empty(); - public async Task DisplayBeforeHotReloadSessionStartAsync() { - if (_originalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) + if (OriginalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) { await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync(); } @@ -51,7 +42,7 @@ public async Task DisplayBeforeHotReloadSessionStartAsync() public async Task DisplayAfterHotReloadSessionEndAsync() { - if (_originalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) + if (OriginalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) { await hotReloadOutputDevice.DisplayAfterHotReloadSessionEndAsync(); } @@ -59,7 +50,7 @@ public async Task DisplayAfterHotReloadSessionEndAsync() public async Task DisplayAfterSessionEndRunAsync() { - await _originalOutputDevice.DisplayAfterSessionEndRunAsync(); + await OriginalOutputDevice.DisplayAfterSessionEndRunAsync(); if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); @@ -68,7 +59,7 @@ public async Task DisplayAfterSessionEndRunAsync() public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { - await _originalOutputDevice.DisplayAsync(producer, data); + await OriginalOutputDevice.DisplayAsync(producer, data); if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.DisplayAsync(producer, data); @@ -77,7 +68,7 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice public async Task DisplayBannerAsync(string? bannerMessage) { - await _originalOutputDevice.DisplayBannerAsync(bannerMessage); + await OriginalOutputDevice.DisplayBannerAsync(bannerMessage); if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.DisplayBannerAsync(bannerMessage); @@ -86,34 +77,15 @@ public async Task DisplayBannerAsync(string? bannerMessage) public async Task DisplayBeforeSessionStartAsync() { - await _originalOutputDevice.DisplayBeforeSessionStartAsync(); + await OriginalOutputDevice.DisplayBeforeSessionStartAsync(); if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.DisplayBeforeSessionStartAsync(); } } - public async Task InitializeAsync() - => await _originalOutputDevice.TryInitializeAsync(); - public async Task IsEnabledAsync() - => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await _originalOutputDevice.IsEnabledAsync(); - - public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, CancellationToken cancellationToken) - { - if (_originalOutputDevice is ITestSessionLifetimeHandler originalLifetimeHandler) - { - await originalLifetimeHandler.OnTestSessionFinishingAsync(sessionUid, cancellationToken); - } - } - - public async Task OnTestSessionStartingAsync(SessionUid sessionUid, CancellationToken cancellationToken) - { - if (_originalOutputDevice is ITestSessionLifetimeHandler originalLifetimeHandler) - { - await originalLifetimeHandler.OnTestSessionStartingAsync(sessionUid, cancellationToken); - } - } + => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await OriginalOutputDevice.IsEnabledAsync(); internal async Task InitializeAsync(ServerTestHost serverTestHost) { @@ -123,14 +95,6 @@ internal async Task InitializeAsync(ServerTestHost serverTestHost) } } - public async Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken) - { - if (_originalOutputDevice is IDataConsumer dataConsumer) - { - await dataConsumer.ConsumeAsync(dataProducer, value, cancellationToken); - } - } - public void Dispose() - => (_originalOutputDevice as IDisposable)?.Dispose(); + => (OriginalOutputDevice as IDisposable)?.Dispose(); } diff --git a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs index bb694a845b8..332590502b6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs @@ -144,8 +144,8 @@ internal static IClock GetSystemClock(this IServiceProvider serviceProvider) internal static ITask GetTask(this IServiceProvider serviceProvider) => serviceProvider.GetRequiredServiceInternal(); - internal static IPlatformOutputDevice GetPlatformOutputDevice(this IServiceProvider serviceProvider) - => serviceProvider.GetRequiredServiceInternal(); + internal static ProxyPlatformOutputDevice GetPlatformOutputDevice(this IServiceProvider serviceProvider) + => serviceProvider.GetRequiredServiceInternal(); internal static IEnvironment GetEnvironment(this IServiceProvider serviceProvider) => serviceProvider.GetRequiredServiceInternal(); From 09aad351727f5bd79d7c5e46373a91022ff8152e Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 12:51:39 +0100 Subject: [PATCH 24/29] Remove unused using --- .../OutputDevice/ProxyPlatformOutputDevice.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs index 370db7ca795..12da7d6f83f 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs @@ -1,7 +1,6 @@ // 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.Extensions; using Microsoft.Testing.Platform.Extensions.OutputDevice; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Hosts; From c2edd6ad59360ff598b33d82913ec3ff67b2fcd6 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 16:29:35 +0100 Subject: [PATCH 25/29] Decouple IOutputDevice from IPlatformOutputDevice --- .../CommandLine/CommandLineHandler.cs | 120 +++++++++--------- .../CommandLine/ICommandLineHandler.cs | 2 +- .../Hosts/CommonTestHost.cs | 6 +- .../Hosts/ConsoleTestHost.cs | 3 +- .../Hosts/ServerTestHost.cs | 6 +- .../Hosts/TestFrameworkBuilderData.cs | 2 - .../Hosts/TestHostBuilder.cs | 38 +++--- .../Hosts/TestHostControllersTestHost.cs | 8 +- .../Hosts/ToolsTestHost.cs | 14 +- .../OutputDevice/IPlatformOutputDevice.cs | 5 +- .../OutputDevice/OutputDeviceManager.cs | 4 +- ...rmOutputDevice.cs => ProxyOutputDevice.cs} | 55 ++------ .../Services/ServiceProviderExtensions.cs | 4 +- 13 files changed, 120 insertions(+), 147 deletions(-) rename src/Platform/Microsoft.Testing.Platform/OutputDevice/{ProxyPlatformOutputDevice.cs => ProxyOutputDevice.cs} (58%) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs index 8fb0dba1bab..f8833150018 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs @@ -51,13 +51,13 @@ public CommandLineHandler(CommandLineParseResult parseResult, IReadOnlyCollectio internal CommandLineParseResult ParseResult { get; } - public async Task PrintInfoAsync(IPlatformOutputDevice platformOutputDevice, IReadOnlyList? availableTools = null) + public async Task PrintInfoAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools = null) { // /!\ Info should not be localized as it serves debugging purposes. await DisplayPlatformInfoAsync(); - await platformOutputDevice.DisplayAsync(this, EmptyText); - await DisplayBuiltInExtensionsInfoAsync(platformOutputDevice); - await platformOutputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, EmptyText); + await DisplayBuiltInExtensionsInfoAsync(outputDevice); + await outputDevice.DisplayAsync(this, EmptyText); List toolExtensions = []; List nonToolExtensions = []; @@ -73,24 +73,24 @@ public async Task PrintInfoAsync(IPlatformOutputDevice platformOutputDevice, IRe } } - await DisplayRegisteredExtensionsInfoAsync(platformOutputDevice, nonToolExtensions); - await platformOutputDevice.DisplayAsync(this, EmptyText); - await DisplayRegisteredToolsInfoAsync(platformOutputDevice, availableTools, toolExtensions); - await platformOutputDevice.DisplayAsync(this, EmptyText); + await DisplayRegisteredExtensionsInfoAsync(outputDevice, nonToolExtensions); + await outputDevice.DisplayAsync(this, EmptyText); + await DisplayRegisteredToolsInfoAsync(outputDevice, availableTools, toolExtensions); + await outputDevice.DisplayAsync(this, EmptyText); return; async Task DisplayPlatformInfoAsync() { // Product title, do not translate. - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData("Microsoft Testing Platform:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Microsoft Testing Platform:")); // TODO: Replace Assembly with IAssembly AssemblyInformationalVersionAttribute? version = Assembly.GetExecutingAssembly().GetCustomAttribute(); string versionInfo = version?.InformationalVersion ?? "Not Available"; - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {versionInfo}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {versionInfo}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Dynamic Code Supported: {_runtimeFeature.IsDynamicCodeSupported}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Dynamic Code Supported: {_runtimeFeature.IsDynamicCodeSupported}")); // TODO: Replace RuntimeInformation with IRuntimeInformation #if NETCOREAPP @@ -98,42 +98,42 @@ async Task DisplayPlatformInfoAsync() #else string runtimeInformation = $"{RuntimeInformation.FrameworkDescription}"; #endif - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime information: {runtimeInformation}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime information: {runtimeInformation}")); #if !NETCOREAPP #pragma warning disable IL3000 // Avoid accessing Assembly file path when publishing as a single file, this branch run only in .NET Framework string runtimeLocation = typeof(object).Assembly?.Location ?? "Not Found"; #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime location: {runtimeLocation}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime location: {runtimeLocation}")); #endif string moduleName = _testApplicationModuleInfo.GetCurrentTestApplicationFullPath(); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Test module: {moduleName}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Test module: {moduleName}")); } - async Task DisplayOptionsAsync(IPlatformOutputDevice platformOutputDevice, IEnumerable options, int indentLevel) + async Task DisplayOptionsAsync(IOutputDevice outputDevice, IEnumerable options, int indentLevel) { string optionNameIndent = new(' ', indentLevel * 2); string optionInfoIndent = new(' ', (indentLevel + 1) * 2); foreach (CommandLineOption option in options.OrderBy(x => x.Name)) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionNameIndent}--{option.Name}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionNameIndent}--{option.Name}")); if (option.Arity.Min == option.Arity.Max) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}")); } else { string maxArityValue = option.Arity.Max == int.MaxValue ? "N" : $"{option.Arity.Max}"; - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}..{maxArityValue}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}..{maxArityValue}")); } - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Hidden: {option.IsHidden}")); - await platformOutputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {option.Description}") { Padding = optionInfoIndent.Length }); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Hidden: {option.IsHidden}")); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {option.Description}") { Padding = optionInfoIndent.Length }); } } - async Task DisplayProvidersAsync(IPlatformOutputDevice platformOutputDevice, IEnumerable optionsProviders, int indentLevel) + async Task DisplayProvidersAsync(IOutputDevice outputDevice, IEnumerable optionsProviders, int indentLevel) { string providerIdIndent = new(' ', indentLevel * 2); string providerInfoIndent = new(' ', (indentLevel + 1) * 2); @@ -145,69 +145,69 @@ async Task DisplayProvidersAsync(IPlatformOutputDevice platformOutputDevice, IEn if (isFirst) { isFirst = false; - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerIdIndent}{provider.Uid}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Name: {provider.DisplayName}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Version: {provider.Version}")); - await platformOutputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {provider.Description}") { Padding = providerInfoIndent.Length }); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Options:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerIdIndent}{provider.Uid}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Name: {provider.DisplayName}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Version: {provider.Version}")); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {provider.Description}") { Padding = providerInfoIndent.Length }); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{providerInfoIndent}Options:")); } - await DisplayOptionsAsync(platformOutputDevice, provider.GetCommandLineOptions(), indentLevel + 2); + await DisplayOptionsAsync(outputDevice, provider.GetCommandLineOptions(), indentLevel + 2); } } } - async Task DisplayBuiltInExtensionsInfoAsync(IPlatformOutputDevice platformOutputDevice) + async Task DisplayBuiltInExtensionsInfoAsync(IOutputDevice outputDevice) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData("Built-in command line providers:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Built-in command line providers:")); if (SystemCommandLineOptionsProviders.Count == 0) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no built-in command line providers.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no built-in command line providers.")); } else { - await DisplayProvidersAsync(platformOutputDevice, SystemCommandLineOptionsProviders, 1); + await DisplayProvidersAsync(outputDevice, SystemCommandLineOptionsProviders, 1); } } - async Task DisplayRegisteredExtensionsInfoAsync(IPlatformOutputDevice platformOutputDevice, List nonToolExtensions) + async Task DisplayRegisteredExtensionsInfoAsync(IOutputDevice outputDevice, List nonToolExtensions) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered command line providers:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered command line providers:")); if (nonToolExtensions.Count == 0) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); } else { - await DisplayProvidersAsync(platformOutputDevice, nonToolExtensions, 1); + await DisplayProvidersAsync(outputDevice, nonToolExtensions, 1); } } - async Task DisplayRegisteredToolsInfoAsync(IPlatformOutputDevice platformOutputDevice, IReadOnlyList? availableTools, List toolExtensions) + async Task DisplayRegisteredToolsInfoAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools, List toolExtensions) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered tools:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered tools:")); if (availableTools is null || availableTools.Count == 0) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered tools.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered tools.")); } else { var groupedToolExtensions = toolExtensions.GroupBy(x => x.ToolName).ToDictionary(x => x.Key, x => x.ToList()); foreach (ITool tool in availableTools.OrderBy(x => x.Uid)) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" {tool.Uid}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Command: {tool.Name}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Name: {tool.DisplayName}")); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {tool.Version}")); - await platformOutputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {tool.Description}") { Padding = 4 }); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(" Tool command line providers:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" {tool.Uid}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Command: {tool.Name}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Name: {tool.DisplayName}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {tool.Version}")); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {tool.Description}") { Padding = 4 }); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" Tool command line providers:")); if (groupedToolExtensions.TryGetValue(tool.Name, out List? providers)) { - await DisplayProvidersAsync(platformOutputDevice, providers, 3); + await DisplayProvidersAsync(outputDevice, providers, 3); } else { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); } } } @@ -232,7 +232,7 @@ public bool TryGetOptionArgumentList(string optionName, [NotNullWhen(true)] out public bool IsDotNetTestPipeInvoked() => IsOptionSet(PlatformCommandLineProvider.DotNetTestPipeOptionKey); #pragma warning disable IDE0060 // Remove unused parameter, temporary we don't use it. - public async Task PrintHelpAsync(IPlatformOutputDevice platformOutputDevice, IReadOnlyList? availableTools = null) + public async Task PrintHelpAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools = null) #pragma warning restore IDE0060 // Remove unused parameter { string applicationName = GetApplicationName(_testApplicationModuleInfo); @@ -240,7 +240,7 @@ public async Task PrintHelpAsync(IPlatformOutputDevice platformOutputDevice, IRe // Temporary disabled, we don't remove the code because could be useful in future. // PrintApplicationToolUsage(availableTools, applicationName); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Empty)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Empty)); // Local functions static string GetApplicationName(ITestApplicationModuleInfo testApplicationModuleInfo) @@ -267,9 +267,9 @@ async Task PrintOptionsAsync(IEnumerable opti foreach (CommandLineOption? option in options) { - await platformOutputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"--{option.Name}") { Padding = 4 }); - await platformOutputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(option.Description) { Padding = 8 }); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Empty)); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"--{option.Name}") { Padding = 4 }); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(option.Description) { Padding = 8 }); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Empty)); } return options.Length != 0; @@ -277,15 +277,15 @@ async Task PrintOptionsAsync(IEnumerable opti async Task PrintApplicationUsageAsync(string applicationName) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.HelpApplicationUsage, applicationName))); - await platformOutputDevice.DisplayAsync(this, EmptyText); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExecuteTestApplication)); - await platformOutputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.HelpApplicationUsage, applicationName))); + await outputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExecuteTestApplication)); + await outputDevice.DisplayAsync(this, EmptyText); RoslynDebug.Assert( !SystemCommandLineOptionsProviders.OfType().Any(), "System command line options should not have any tool option registered."); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)); ICommandLineOptionsProvider[] nonToolsExtensionProviders = ExtensionsCommandLineOptionsProviders .Where(provider => provider is not IToolCommandLineOptionsProvider) @@ -293,15 +293,15 @@ async Task PrintApplicationUsageAsync(string applicationName) // By default, only system options are built-in but some extensions (e.g. retry) are considered as built-in too, // so we need to union the 2 collections before printing the options. await PrintOptionsAsync(SystemCommandLineOptionsProviders.Union(nonToolsExtensionProviders), 1, builtInOnly: true); - await platformOutputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, EmptyText); - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExtensionOptions)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExtensionOptions)); if (!await PrintOptionsAsync(nonToolsExtensionProviders, 1)) { - await platformOutputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpNoExtensionRegistered)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpNoExtensionRegistered)); } - await platformOutputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, EmptyText); } // Temporary disabled, we don't remove the code because could be useful in future. diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ICommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ICommandLineHandler.cs index 97cb900e77c..eb91a4513d2 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ICommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ICommandLineHandler.cs @@ -10,5 +10,5 @@ internal interface ICommandLineHandler { bool IsHelpInvoked(); - Task PrintHelpAsync(IPlatformOutputDevice platformOutputDevice, IReadOnlyList? availableTools = null); + Task PrintHelpAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools = null); } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 71ef8d5bc56..0f3fd2b5198 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -119,7 +119,7 @@ private async Task RunTestAppAsync(CancellationToken testApplicationCancell protected abstract Task InternalRunAsync(); - protected static async Task ExecuteRequestAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext testSessionInfo, + protected static async Task ExecuteRequestAsync(ProxyOutputDevice outputDevice, ITestSessionContext testSessionInfo, ServiceProvider serviceProvider, BaseMessageBus baseMessageBus, ITestFramework testFramework, TestHost.ClientInfo client) { CancellationToken testSessionCancellationToken = serviceProvider.GetTestSessionContext().CancellationToken; @@ -142,7 +142,7 @@ protected static async Task ExecuteRequestAsync(ProxyPlatformOutputDevice output await DisplayAfterSessionEndRunAsync(outputDevice, testSessionInfo, testSessionCancellationToken); } - private static async Task DisplayBeforeSessionStartAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) + private static async Task DisplayBeforeSessionStartAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display before session start await outputDevice.DisplayBeforeSessionStartAsync(); @@ -155,7 +155,7 @@ await testSessionLifetimeHandler.OnTestSessionStartingAsync( } } - private static async Task DisplayAfterSessionEndRunAsync(ProxyPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) + private static async Task DisplayAfterSessionEndRunAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display after session end await outputDevice.DisplayAfterSessionEndRunAsync(); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs index 15adebb7ff9..4a66392d2b8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs @@ -10,6 +10,7 @@ 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; @@ -83,7 +84,7 @@ protected override async Task InternalRunAsync() ITestSessionContext testSessionInfo = ServiceProvider.GetTestSessionContext(); await ExecuteRequestAsync( - ServiceProvider.GetPlatformOutputDevice(), + (ProxyOutputDevice)ServiceProvider.GetOutputDevice(), testSessionInfo, ServiceProvider, ServiceProvider.GetBaseMessageBus(), diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index bec826c83fb..a9cdb426f3a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -477,7 +477,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s DateTimeOffset adapterLoadStart = _clock.UtcNow; - ProxyPlatformOutputDevice outputDevice = ServiceProvider.GetRequiredService(); + ProxyOutputDevice outputDevice = ServiceProvider.GetRequiredService(); await outputDevice.InitializeAsync(this); // Build the per request adapter @@ -486,7 +486,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s requestFactory, invoker, filterFactory, - outputDevice, + outputDevice.OriginalOutputDevice, [testNodeUpdateProcessor], _testFrameworkManager, _testSessionManager, @@ -505,7 +505,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s // Execute the request await ExecuteRequestAsync( - perRequestServiceProvider.GetPlatformOutputDevice(), + outputDevice, perRequestServiceProvider.GetTestSessionContext(), perRequestServiceProvider, perRequestServiceProvider.GetBaseMessageBus(), diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs index bdc541505df..838dc78ef3f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestFrameworkBuilderData.cs @@ -28,8 +28,6 @@ internal class TestFrameworkBuilderData(ServiceProvider serviceProvider, ITestEx public IPlatformOutputDevice PlatformOutputDisplayService { get; } = platformOutputDisplayService; - internal IPlatformOutputDevice OriginalPlatformOutputDisplayService => ((ProxyPlatformOutputDevice)PlatformOutputDisplayService).OriginalOutputDevice; - public IEnumerable ServerPerCallConsumers { get; } = serverPerCallConsumers; public TestFrameworkManager TestFrameworkManager { get; } = testFrameworkManager; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index dd83b3d50ac..bc0a2184dfa 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -209,7 +209,7 @@ public async Task BuildAsync( bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); - ProxyPlatformOutputDevice platformOutputDevice = await ((PlatformOutputDeviceManager)OutputDisplay).BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol); + ProxyOutputDevice proxyOutputDevice = await ((PlatformOutputDeviceManager)OutputDisplay).BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol); // Add FileLoggerProvider if needed if (loggingState.FileLoggerProvider is not null) @@ -227,13 +227,14 @@ public async Task BuildAsync( loggerFactoryProxy.SetLoggerFactory(loggerFactory); // Initialize the output device if needed. - if (await platformOutputDevice.OriginalOutputDevice.IsEnabledAsync()) + if (await proxyOutputDevice.OriginalOutputDevice.IsEnabledAsync()) { - await platformOutputDevice.OriginalOutputDevice.TryInitializeAsync(); + await proxyOutputDevice.OriginalOutputDevice.TryInitializeAsync(); } // Add the platform output device to the service provider for both modes. - serviceProvider.TryAddService(platformOutputDevice); + serviceProvider.TryAddService(proxyOutputDevice); + serviceProvider.TryAddService(proxyOutputDevice.OriginalOutputDevice); // Create the test framework capabilities ITestFrameworkCapabilities testFrameworkCapabilities = TestFramework.TestFrameworkCapabilitiesFactory(serviceProvider); @@ -254,9 +255,9 @@ public async Task BuildAsync( if (!loggingState.CommandLineParseResult.HasTool && !commandLineValidationResult.IsValid) { - await DisplayBannerIfEnabledAsync(loggingState, platformOutputDevice, testFrameworkCapabilities); - await platformOutputDevice.DisplayAsync(commandLineHandler, new ErrorMessageOutputDeviceData(commandLineValidationResult.ErrorMessage)); - await commandLineHandler.PrintHelpAsync(platformOutputDevice); + await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities); + await proxyOutputDevice.DisplayAsync(commandLineHandler, new ErrorMessageOutputDeviceData(commandLineValidationResult.ErrorMessage)); + await commandLineHandler.PrintHelpAsync(proxyOutputDevice); return new InformativeCommandLineTestHost(ExitCodes.InvalidCommandLine, serviceProvider); } @@ -292,7 +293,7 @@ public async Task BuildAsync( // Display banner now because we need capture the output in case of MSBuild integration and we want to forward // to file disc also the banner, so at this point we need to have all services and configuration(result directory) built. - await DisplayBannerIfEnabledAsync(loggingState, platformOutputDevice, testFrameworkCapabilities); + await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities); // Add global telemetry service. // Add at this point or the telemetry banner appearance order will be wrong, we want the testing app banner before the telemetry banner. @@ -311,7 +312,7 @@ public async Task BuildAsync( // Register the ITestApplicationResult TestApplicationResult testApplicationResult = new( - platformOutputDevice, + proxyOutputDevice, serviceProvider.GetTestApplicationCancellationTokenSource(), serviceProvider.GetCommandLineOptions(), serviceProvider.GetEnvironment()); @@ -324,14 +325,14 @@ public async Task BuildAsync( // ======= TOOLS MODE ======== // // Add the platform output device to the service provider. var toolsServiceProvider = (ServiceProvider)serviceProvider.Clone(); - toolsServiceProvider.TryAddService(platformOutputDevice); + toolsServiceProvider.TryAddService(proxyOutputDevice); IReadOnlyList toolsInformation = await ((ToolsManager)Tools).BuildAsync(toolsServiceProvider); if (loggingState.CommandLineParseResult.HasTool) { // Add the platform output device to the service provider. - serviceProvider.TryAddService(platformOutputDevice); + serviceProvider.TryAddService(proxyOutputDevice); - ToolsTestHost toolsTestHost = new(toolsInformation, serviceProvider, commandLineHandler, platformOutputDevice); + ToolsTestHost toolsTestHost = new(toolsInformation, serviceProvider, commandLineHandler, proxyOutputDevice); await LogTestHostCreatedAsync( serviceProvider, @@ -358,7 +359,7 @@ await LogTestHostCreatedAsync( } else { - await commandLineHandler.PrintHelpAsync(platformOutputDevice, toolsInformation); + await commandLineHandler.PrintHelpAsync(proxyOutputDevice, toolsInformation); } return new InformativeCommandLineTestHost(0, serviceProvider); @@ -367,7 +368,7 @@ await LogTestHostCreatedAsync( // If --info is invoked we return if (commandLineHandler.IsInfoInvoked()) { - await commandLineHandler.PrintInfoAsync(platformOutputDevice, toolsInformation); + await commandLineHandler.PrintInfoAsync(proxyOutputDevice, toolsInformation); return new InformativeCommandLineTestHost(0, serviceProvider); } @@ -402,7 +403,7 @@ await LogTestHostCreatedAsync( var testHostControllersServiceProvider = (ServiceProvider)serviceProvider.Clone(); // Add the platform output device to the service provider. - testHostControllersServiceProvider.TryAddService(platformOutputDevice); + testHostControllersServiceProvider.TryAddService(proxyOutputDevice); // Add the message bus proxy specific for the launchers. testHostControllersServiceProvider.TryAddService(new MessageBusProxy()); @@ -643,7 +644,7 @@ private async Task BuildTestFrameworkAsync(TestFrameworkBuilderD // creations and we could lose interesting diagnostic information. List dataConsumersBuilder = []; - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.OriginalPlatformOutputDisplayService, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.PlatformOutputDisplayService, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestFactory, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestInvoker, serviceProvider, dataConsumersBuilder); await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionFilterFactory, serviceProvider, dataConsumersBuilder); @@ -817,7 +818,7 @@ private async Task RegisterAsServiceOrConsumerOrBothAsync(object service, Servic await AddServiceIfNotSkippedAsync(service, serviceProvider); } - private async Task DisplayBannerIfEnabledAsync(ApplicationLoggingState loggingState, IPlatformOutputDevice platformOutputDevice, + private async Task DisplayBannerIfEnabledAsync(ApplicationLoggingState loggingState, ProxyOutputDevice outputDevice, ITestFrameworkCapabilities testFrameworkCapabilities) { bool isNoBannerSet = loggingState.CommandLineParseResult.IsOptionSet(PlatformCommandLineProvider.NoBannerOptionKey); @@ -829,7 +830,8 @@ private async Task DisplayBannerIfEnabledAsync(ApplicationLoggingState loggingSt string? bannerMessage = bannerMessageOwnerCapability is not null ? await bannerMessageOwnerCapability.GetBannerMessageAsync() : null; - await platformOutputDevice.DisplayBannerAsync(bannerMessage); + + await outputDevice.DisplayBannerAsync(bannerMessage); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index baa794cb23b..9ee0415152a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -77,7 +77,7 @@ protected override async Task InternalRunAsync() ITelemetryCollector telemetry = ServiceProvider.GetTelemetryCollector(); ITelemetryInformation telemetryInformation = ServiceProvider.GetTelemetryInformation(); string? extensionInformation = null; - IPlatformOutputDevice platformOutputDevice = ServiceProvider.GetPlatformOutputDevice(); + var outputDevice = (ProxyOutputDevice)ServiceProvider.GetOutputDevice(); IConfiguration configuration = ServiceProvider.GetConfiguration(); try { @@ -203,7 +203,7 @@ protected override async Task InternalRunAsync() displayErrorMessageBuilder.AppendLine(CultureInfo.InvariantCulture, $"Provider '{extension.DisplayName}' (UID: {extension.Uid}) failed with error: {errorMessage}"); } - await platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(displayErrorMessageBuilder.ToString())); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(displayErrorMessageBuilder.ToString())); await _logger.LogErrorAsync(logErrorMessageBuilder.ToString()); return ExitCodes.InvalidPlatformSetup; } @@ -306,7 +306,7 @@ protected override async Task InternalRunAsync() await messageBusProxy.DisableAsync(); } - await platformOutputDevice.DisplayAfterSessionEndRunAsync(); + await outputDevice.DisplayAfterSessionEndRunAsync(); // We collect info about the extensions before the dispose to avoid possible issue with cleanup. if (telemetryInformation.IsEnabled) @@ -322,7 +322,7 @@ protected override async Task InternalRunAsync() if (!_testHostGracefullyClosed && !abortRun.IsCancellationRequested) { - await platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.TestProcessDidNotExitGracefullyErrorMessage, exitCode))); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.TestProcessDidNotExitGracefullyErrorMessage, exitCode))); } await _logger.LogInformationAsync($"TestHostControllersTestHost ended with exit code '{exitCode}' (real test host exit code '{testHostProcess.ExitCode}')' in '{consoleRunStarted.Elapsed}'"); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs index d39d0476762..b0ed844cc8e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs @@ -20,12 +20,12 @@ internal sealed class ToolsTestHost( IReadOnlyList toolsInformation, ServiceProvider serviceProvider, CommandLineHandler commandLineHandler, - IPlatformOutputDevice platformOutputDevice) : ITestHost, IOutputDeviceDataProducer + IOutputDevice outputDevice) : ITestHost, IOutputDeviceDataProducer { private readonly IReadOnlyList _toolsInformation = toolsInformation; private readonly ServiceProvider _serviceProvider = serviceProvider; private readonly CommandLineHandler _commandLineHandler = commandLineHandler; - private readonly IPlatformOutputDevice _platformOutputDevice = platformOutputDevice; + private readonly IOutputDevice _outputDevice = outputDevice; /// public string Uid => nameof(ToolsTestHost); @@ -64,21 +64,21 @@ public async Task RunAsync() { if (UnknownOptions(out string? unknownOptionsError, tool)) { - await _platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(unknownOptionsError)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(unknownOptionsError)); console.WriteLine(); return ExitCodes.InvalidCommandLine; } if (ExtensionArgumentArityAreInvalid(out string? arityErrors, tool)) { - await _platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(arityErrors)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(arityErrors)); return ExitCodes.InvalidCommandLine; } ValidationResult optionsArgumentsValidationResult = await ValidateOptionsArgumentsAsync(tool); if (!optionsArgumentsValidationResult.IsValid) { - await _platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(optionsArgumentsValidationResult.ErrorMessage)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(optionsArgumentsValidationResult.ErrorMessage)); return ExitCodes.InvalidCommandLine; } @@ -86,8 +86,8 @@ public async Task RunAsync() } } - await _platformOutputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData($"Tool '{toolNameToRun}' not found in the list of registered tools.")); - await _commandLineHandler.PrintHelpAsync(_platformOutputDevice); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData($"Tool '{toolNameToRun}' not found in the list of registered tools.")); + await _commandLineHandler.PrintHelpAsync(_outputDevice); return ExitCodes.InvalidCommandLine; } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/IPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/IPlatformOutputDevice.cs index ac87b96c2a7..25d1bf12ae1 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/IPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/IPlatformOutputDevice.cs @@ -2,14 +2,17 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.Extensions; +using Microsoft.Testing.Platform.Extensions.OutputDevice; namespace Microsoft.Testing.Platform.OutputDevice; -internal interface IPlatformOutputDevice : IExtension, IOutputDevice +internal interface IPlatformOutputDevice : IExtension { Task DisplayBannerAsync(string? bannerMessage); Task DisplayBeforeSessionStartAsync(); Task DisplayAfterSessionEndRunAsync(); + + Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data); } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index de83e7543ff..d3e09c4e8b9 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -16,7 +16,7 @@ public void SetPlatformOutputDevice(Func BuildAsync(ServiceProvider serviceProvider, bool useServerModeOutputDevice) + internal async Task BuildAsync(ServiceProvider serviceProvider, bool useServerModeOutputDevice) { // TODO: SetPlatformOutputDevice isn't public yet. // Before exposing it, do we want to pass the "useServerModeOutputDevice" info to it? @@ -30,7 +30,7 @@ internal async Task BuildAsync(ServiceProvider servic nonServerOutputDevice = GetDefaultTerminalOutputDevice(serviceProvider); } - return new ProxyPlatformOutputDevice(nonServerOutputDevice, useServerModeOutputDevice ? new ServerModePerCallOutputDevice(serviceProvider) : null); + return new ProxyOutputDevice(nonServerOutputDevice, useServerModeOutputDevice ? new ServerModePerCallOutputDevice(serviceProvider) : null); } public static TerminalOutputDevice GetDefaultTerminalOutputDevice(ServiceProvider serviceProvider) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs similarity index 58% rename from src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs rename to src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs index 12da7d6f83f..75098f1358f 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyPlatformOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs @@ -2,7 +2,6 @@ // 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.Hosts; using Microsoft.Testing.Platform.ServerMode; @@ -11,11 +10,11 @@ namespace Microsoft.Testing.Platform.OutputDevice; // Any interfaces that can have special treatment for any output device should be implemented by // this proxy class and be forwarded properly. // This is not so good. How can we make sure we are not missing any interfaces that may be implemented by external output devices? -internal sealed class ProxyPlatformOutputDevice : IHotReloadPlatformOutputDevice, IDisposable +internal sealed class ProxyOutputDevice : IOutputDevice { private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; - public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, ServerModePerCallOutputDevice? serverModeOutputDevice) + public ProxyOutputDevice(IPlatformOutputDevice originalOutputDevice, ServerModePerCallOutputDevice? serverModeOutputDevice) { OriginalOutputDevice = originalOutputDevice; _serverModeOutputDevice = serverModeOutputDevice; @@ -23,39 +22,6 @@ public ProxyPlatformOutputDevice(IPlatformOutputDevice originalOutputDevice, Ser internal IPlatformOutputDevice OriginalOutputDevice { get; } - public string Uid => nameof(ProxyPlatformOutputDevice); - - public string Version => AppVersion.DefaultSemVer; - - public string DisplayName => nameof(ProxyPlatformOutputDevice); - - public string Description => nameof(ProxyPlatformOutputDevice); - - public async Task DisplayBeforeHotReloadSessionStartAsync() - { - if (OriginalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) - { - await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync(); - } - } - - public async Task DisplayAfterHotReloadSessionEndAsync() - { - if (OriginalOutputDevice is IHotReloadPlatformOutputDevice hotReloadOutputDevice) - { - await hotReloadOutputDevice.DisplayAfterHotReloadSessionEndAsync(); - } - } - - public async Task DisplayAfterSessionEndRunAsync() - { - await OriginalOutputDevice.DisplayAfterSessionEndRunAsync(); - if (_serverModeOutputDevice is not null) - { - await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); - } - } - public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { await OriginalOutputDevice.DisplayAsync(producer, data); @@ -65,7 +31,7 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice } } - public async Task DisplayBannerAsync(string? bannerMessage) + internal async Task DisplayBannerAsync(string? bannerMessage) { await OriginalOutputDevice.DisplayBannerAsync(bannerMessage); if (_serverModeOutputDevice is not null) @@ -74,7 +40,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) } } - public async Task DisplayBeforeSessionStartAsync() + internal async Task DisplayBeforeSessionStartAsync() { await OriginalOutputDevice.DisplayBeforeSessionStartAsync(); if (_serverModeOutputDevice is not null) @@ -83,8 +49,14 @@ public async Task DisplayBeforeSessionStartAsync() } } - public async Task IsEnabledAsync() - => (_serverModeOutputDevice is not null && await _serverModeOutputDevice.IsEnabledAsync()) || await OriginalOutputDevice.IsEnabledAsync(); + internal async Task DisplayAfterSessionEndRunAsync() + { + await OriginalOutputDevice.DisplayAfterSessionEndRunAsync(); + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); + } + } internal async Task InitializeAsync(ServerTestHost serverTestHost) { @@ -93,7 +65,4 @@ internal async Task InitializeAsync(ServerTestHost serverTestHost) await _serverModeOutputDevice.InitializeAsync(serverTestHost); } } - - public void Dispose() - => (OriginalOutputDevice as IDisposable)?.Dispose(); } diff --git a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs index 332590502b6..bb694a845b8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProviderExtensions.cs @@ -144,8 +144,8 @@ internal static IClock GetSystemClock(this IServiceProvider serviceProvider) internal static ITask GetTask(this IServiceProvider serviceProvider) => serviceProvider.GetRequiredServiceInternal(); - internal static ProxyPlatformOutputDevice GetPlatformOutputDevice(this IServiceProvider serviceProvider) - => serviceProvider.GetRequiredServiceInternal(); + internal static IPlatformOutputDevice GetPlatformOutputDevice(this IServiceProvider serviceProvider) + => serviceProvider.GetRequiredServiceInternal(); internal static IEnvironment GetEnvironment(this IServiceProvider serviceProvider) => serviceProvider.GetRequiredServiceInternal(); From 59fd67aa60a8429666ff288d7719aeedb7ba4c3f Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Tue, 3 Dec 2024 17:55:59 +0100 Subject: [PATCH 26/29] Avoid async void --- .../Hosts/ServerTestHost.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index a9cdb426f3a..14f572db15a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -104,30 +104,28 @@ public ServerTestHost( public string Description => PlatformResources.ServerTestHostDescription; -#pragma warning disable VSTHRD100 // Avoid async void methods - private async void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) -#pragma warning restore VSTHRD100 // Avoid async void methods + private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { _logger.LogWarning($"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}"); // Looks like nothing in this message to really be localized? // All are class names, method names, property names, and placeholders. So none is localizable? - await ServiceProvider.GetOutputDevice().DisplayAsync( + ServiceProvider.GetOutputDevice().DisplayAsync( this, new WarningMessageOutputDeviceData( - $"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}")); + $"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}")) + .GetAwaiter().GetResult(); } -#pragma warning disable VSTHRD100 // Avoid async void methods - private async void OnTaskSchedulerUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) -#pragma warning restore VSTHRD100 // Avoid async void methods + private void OnTaskSchedulerUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) { e.SetObserved(); _logger.LogWarning($"[ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {e.Exception}"); // Looks like nothing in this message to really be localized? // All are class names, method names, property names, and placeholders. So none is localizable? - await ServiceProvider.GetOutputDevice().DisplayAsync(this, new WarningMessageOutputDeviceData(PlatformResources.UnobservedTaskExceptionWarningMessage)); + ServiceProvider.GetOutputDevice().DisplayAsync(this, new WarningMessageOutputDeviceData(PlatformResources.UnobservedTaskExceptionWarningMessage)) + .GetAwaiter().GetResult(); } [MemberNotNull(nameof(_messageHandler))] From 26964af45b38da6072d1f13503c46524e1aad222 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Wed, 4 Dec 2024 11:17:04 +0100 Subject: [PATCH 27/29] Fix race --- .../Microsoft.Testing.Platform/Hosts/CommonTestHost.cs | 6 +++++- .../Microsoft.Testing.Platform/Hosts/ServerTestHost.cs | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 0f3fd2b5198..0e146d7e9c5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -69,7 +69,11 @@ public async Task RunAsync() await DisposeServiceProviderAsync(ServiceProvider, isProcessShutdown: true); await DisposeHelper.DisposeAsync(ServiceProvider.GetService()); await DisposeHelper.DisposeAsync(PushOnlyProtocol); - await DisposeHelper.DisposeAsync(ServiceProvider.GetTestApplicationCancellationTokenSource()); + + // This is intentional that we are not disposing the CTS. + // An unobserved task exception could be raised after the dispose, and we want to use OutputDevice there + // which needs CTS down the path. + // await DisposeHelper.DisposeAsync(ServiceProvider.GetTestApplicationCancellationTokenSource()); } if (testApplicationCancellationToken.IsCancellationRequested) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 14f572db15a..6830454be0a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -660,6 +660,11 @@ public void Dispose() { // Note: The lifetime of the _reader/_writer should be currently handled by the RunAsync() // We could consider creating a stateful engine that has the lifetime == server connection UP. + if (!ServiceProvider.GetUnhandledExceptionsPolicy().FastFailOnFailure) + { + AppDomain.CurrentDomain.UnhandledException -= OnCurrentDomainUnhandledException; + TaskScheduler.UnobservedTaskException -= OnTaskSchedulerUnobservedTaskException; + } } internal async Task SendTestUpdateCompleteAsync(Guid runId) From 39971bdab2be545acf170cef22654d85aa430fb8 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Wed, 4 Dec 2024 11:44:30 +0100 Subject: [PATCH 28/29] Address review comments --- .../Hosts/ServerTestHost.cs | 8 +++++--- .../OutputDevice/ProxyOutputDevice.cs | 11 ++++++++--- .../OutputDevice/TerminalOutputDevice.cs | 1 - .../Resources/PlatformResources.resx | 4 ++++ .../Resources/xlf/PlatformResources.cs.xlf | 5 +++++ .../Resources/xlf/PlatformResources.de.xlf | 5 +++++ .../Resources/xlf/PlatformResources.es.xlf | 5 +++++ .../Resources/xlf/PlatformResources.fr.xlf | 5 +++++ .../Resources/xlf/PlatformResources.it.xlf | 5 +++++ .../Resources/xlf/PlatformResources.ja.xlf | 5 +++++ .../Resources/xlf/PlatformResources.ko.xlf | 5 +++++ .../Resources/xlf/PlatformResources.pl.xlf | 5 +++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 5 +++++ .../Resources/xlf/PlatformResources.ru.xlf | 5 +++++ .../Resources/xlf/PlatformResources.tr.xlf | 5 +++++ .../Resources/xlf/PlatformResources.zh-Hans.xlf | 5 +++++ .../Resources/xlf/PlatformResources.zh-Hant.xlf | 5 +++++ ...esting.Platform.Acceptance.IntegrationTests.csproj | 3 +-- 18 files changed, 83 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 6830454be0a..78f85cbb467 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Net.Sockets; using Microsoft.Testing.Internal.Framework; @@ -287,13 +288,14 @@ private async Task HandleNotificationAsync(NotificationMessage message, Cancella Exception? cancellationException = rpcState.CancelRequest(); if (cancellationException is null) { + // This is intentionally not using PlatformResources.ExceptionDuringCancellationWarningMessage + // It's meant for troubleshooting and shouldn't be localized. + // The localized message that is user-facing will be displayed in the DisplayAsync call next line. await _logger.LogWarningAsync($"Exception during the cancellation of request id '{args.CancelRequestId}'"); - // TODO: Localize await ServiceProvider.GetOutputDevice().DisplayAsync( this, - new WarningMessageOutputDeviceData( - $"Exception during the cancellation of request id '{args.CancelRequestId}'")); + new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExceptionDuringCancellationWarningMessage, args.CancelRequestId))); } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs index 75098f1358f..92289a80dea 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs @@ -7,9 +7,6 @@ namespace Microsoft.Testing.Platform.OutputDevice; -// Any interfaces that can have special treatment for any output device should be implemented by -// this proxy class and be forwarded properly. -// This is not so good. How can we make sure we are not missing any interfaces that may be implemented by external output devices? internal sealed class ProxyOutputDevice : IOutputDevice { private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; @@ -60,6 +57,14 @@ internal async Task DisplayAfterSessionEndRunAsync() internal async Task InitializeAsync(ServerTestHost serverTestHost) { + // Server mode output device is basically used to send messages to Test Explorer. + // For that, it needs the ServerTestHost. + // However, the ServerTestHost is available later than the time we create the output device. + // So, the server mode output device is initially created early without the ServerTestHost, and + // it keeps any messages in a list. + // Later when ServerTestHost is created and is available, we initialize the server mode output device. + // The initialization will setup the right state for pushing to Test Explorer, and will push any existing + // messages to Test Explorer as well. if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.InitializeAsync(serverTestHost); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 76bf420b5f3..05b5a39fc33 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -25,7 +25,6 @@ namespace Microsoft.Testing.Platform.OutputDevice; /// /// Implementation of output device that writes to terminal with progress and optionally with ANSI. /// -// NOTE: !!! Any interfaces here will likely need to be implemented by ProxyPlatformOutputDevice as well. !!! internal partial class TerminalOutputDevice : IHotReloadPlatformOutputDevice, IDataConsumer, IOutputDeviceDataProducer, diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 2e83f07dcb0..3ae6c7d53f7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -690,4 +690,8 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} {0} is the exception that was unhandled/unobserved + + Exception during the cancellation of request id '{0}' + {0} is the request id + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index f0509501c1c..4526c310899 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -219,6 +219,11 @@ Zprostředkovatel {0} (UID: {1}) selhal s chybou: {2}. + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Ukončovací kód diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 5bc30251c71..3efbd66304a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -219,6 +219,11 @@ Anbieter "{0}" (UID: {1}) ist mit folgendem Fehler fehlgeschlagen: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Exitcode diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index a39e942c098..3530bac97a9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -219,6 +219,11 @@ Error del proveedor "{0}" (UID: {1}) con el error: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Código de salida diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 374079d0464..2b23f3d009e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -219,6 +219,11 @@ Désolé, échec de l’« {0} » du fournisseur (UID : {1}) avec l’erreur : {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Code de sortie diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index 52c39cb9ba2..f8450b75344 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -219,6 +219,11 @@ Provider '{0}' (UID: {1}) non riuscito con errore: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Codice di uscita diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 69393fd613e..6411ac94052 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -219,6 +219,11 @@ プロバイダー '{0}' (UID: {1}) が次のエラーで失敗しました: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code 終了コード diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index bd0c61bb7ee..0ea7a1e9b4b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -219,6 +219,11 @@ 공급자 '{0}'(UID: {1})이 오류 {2}(으)로 실패했습니다. + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code 종료 코드 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index d1e0325506a..ca298da8b60 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -219,6 +219,11 @@ Dostawca „{0}” (UID:{1}) nie powiódł się z powodu błędu: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Kod zakończenia diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 16761f8a18c..d3039301049 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -219,6 +219,11 @@ O provedor ''{0}'' (UID: {1}) falhou com o erro: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Código de saída diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 598c726e44e..42539f5b673 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -219,6 +219,11 @@ Сбой поставщика "{0}" (ИД пользователя: {1}) с ошибкой: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Код завершения diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index e6de38c0c63..91326a0e253 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -219,6 +219,11 @@ '{0}' sağlayıcısı '' (UID: {1}) şu hatayla başarısız oldu: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code Çıkış kodu diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 69a3b6048d4..3ee2239188f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -219,6 +219,11 @@ 提供程序 '{0}' (UID: {1}) 失败,出现错误: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code 退出代码 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index d414fb2731a..14f04644b52 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -219,6 +219,11 @@ 提供者 '{0}' (UID: {1}) 失敗,發生錯誤: {2} + + Exception during the cancellation of request id '{0}' + Exception during the cancellation of request id '{0}' + {0} is the request id + Exit code 結束代碼 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj index b08eb6c5d11..46050c43b2a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj @@ -5,7 +5,6 @@ $(TestRunnerAdditionalArguments) --retry-failed-tests 3 false $(DefineConstants);SKIP_INTERMEDIATE_TARGET_FRAMEWORKS - $(DefineConstants);IS_MTP Exe true @@ -15,7 +14,7 @@ - + From e3e2907e9bafff6815ad63cb757253f6f30542f8 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Wed, 4 Dec 2024 11:46:11 +0100 Subject: [PATCH 29/29] Move comment to server mode output device --- .../OutputDevice/ProxyOutputDevice.cs | 8 -------- .../ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs | 8 ++++++++ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs index 92289a80dea..6896debd84a 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs @@ -57,14 +57,6 @@ internal async Task DisplayAfterSessionEndRunAsync() internal async Task InitializeAsync(ServerTestHost serverTestHost) { - // Server mode output device is basically used to send messages to Test Explorer. - // For that, it needs the ServerTestHost. - // However, the ServerTestHost is available later than the time we create the output device. - // So, the server mode output device is initially created early without the ServerTestHost, and - // it keeps any messages in a list. - // Later when ServerTestHost is created and is available, we initialize the server mode output device. - // The initialization will setup the right state for pushing to Test Explorer, and will push any existing - // messages to Test Explorer as well. if (_serverModeOutputDevice is not null) { await _serverModeOutputDevice.InitializeAsync(serverTestHost); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 176a37a3e9e..091f782ad38 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -29,6 +29,14 @@ public ServerModePerCallOutputDevice(IServiceProvider serviceProvider) internal async Task InitializeAsync(IServerTestHost serverTestHost) { + // Server mode output device is basically used to send messages to Test Explorer. + // For that, it needs the ServerTestHost. + // However, the ServerTestHost is available later than the time we create the output device. + // So, the server mode output device is initially created early without the ServerTestHost, and + // it keeps any messages in a list. + // Later when ServerTestHost is created and is available, we initialize the server mode output device. + // The initialization will setup the right state for pushing to Test Explorer, and will push any existing + // messages to Test Explorer as well. _serverTestHost = serverTestHost; foreach (ServerLogMessage message in _messages)