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 15ea8f2ccd1..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) @@ -119,7 +123,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(ProxyOutputDevice outputDevice, ITestSessionContext testSessionInfo, ServiceProvider serviceProvider, BaseMessageBus baseMessageBus, ITestFramework testFramework, TestHost.ClientInfo client) { CancellationToken testSessionCancellationToken = serviceProvider.GetTestSessionContext().CancellationToken; @@ -142,12 +146,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(ProxyOutputDevice 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 +159,13 @@ await testSessionLifetimeHandler.OnTestSessionStartingAsync( } } - private static async Task DisplayAfterSessionEndRunAsync(IPlatformOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) + private static async Task DisplayAfterSessionEndRunAsync(ProxyOutputDevice 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/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 68d8a1b8eb9..78f85cbb467 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -3,16 +3,20 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Net.Sockets; 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 +24,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 +97,36 @@ public ServerTestHost( protected override bool RunTestApplicationLifeCycleCallbacks => true; + public string Uid => nameof(ServerTestHost); + + public string Version => AppVersion.DefaultSemVer; + + public string DisplayName => PlatformResources.ServerTestHostDisplayName; + + public string Description => PlatformResources.ServerTestHostDescription; + private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) - => _logger.LogWarning($"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}"); + { + _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? + ServiceProvider.GetOutputDevice().DisplayAsync( + this, + new WarningMessageOutputDeviceData( + $"[ServerTestHost.OnCurrentDomainUnhandledException] {e.ExceptionObject}{_environment.NewLine}IsTerminating: {e.IsTerminating}")) + .GetAwaiter().GetResult(); + } 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? + ServiceProvider.GetOutputDevice().DisplayAsync(this, new WarningMessageOutputDeviceData(PlatformResources.UnobservedTaskExceptionWarningMessage)) + .GetAwaiter().GetResult(); } [MemberNotNull(nameof(_messageHandler))] @@ -118,13 +145,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(); @@ -268,7 +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}'"); + + await ServiceProvider.GetOutputDevice().DisplayAsync( + this, + new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExceptionDuringCancellationWarningMessage, args.CancelRequestId))); } } @@ -450,13 +477,16 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s DateTimeOffset adapterLoadStart = _clock.UtcNow; + ProxyOutputDevice outputDevice = ServiceProvider.GetRequiredService(); + await outputDevice.InitializeAsync(this); + // Build the per request adapter - ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new( + ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new TestFrameworkBuilderData( perRequestServiceProvider, requestFactory, invoker, filterFactory, - new ServerModePerCallOutputDevice(), + outputDevice.OriginalOutputDevice, [testNodeUpdateProcessor], _testFrameworkManager, _testSessionManager, @@ -475,7 +505,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s // Execute the request await ExecuteRequestAsync( - perRequestServiceProvider.GetPlatformOutputDevice(), + outputDevice, perRequestServiceProvider.GetTestSessionContext(), perRequestServiceProvider, perRequestServiceProvider.GetBaseMessageBus(), @@ -632,6 +662,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) @@ -700,6 +735,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/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index ff997646949..bc0a2184dfa 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,11 @@ 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); + + ProxyOutputDevice proxyOutputDevice = await ((PlatformOutputDeviceManager)OutputDisplay).BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol); + // Add FileLoggerProvider if needed if (loggingState.FileLoggerProvider is not null) { @@ -219,16 +220,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); @@ -236,19 +227,14 @@ public async Task BuildAsync( loggerFactoryProxy.SetLoggerFactory(loggerFactory); // Initialize the output device if needed. - if (await platformOutputDevice.IsEnabledAsync()) + if (await proxyOutputDevice.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 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); @@ -269,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); } @@ -307,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. @@ -326,7 +312,7 @@ public async Task BuildAsync( // Register the ITestApplicationResult TestApplicationResult testApplicationResult = new( - platformOutputDevice, + proxyOutputDevice, serviceProvider.GetTestApplicationCancellationTokenSource(), serviceProvider.GetCommandLineOptions(), serviceProvider.GetEnvironment()); @@ -339,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, @@ -373,7 +359,7 @@ await LogTestHostCreatedAsync( } else { - await commandLineHandler.PrintHelpAsync(platformOutputDevice, toolsInformation); + await commandLineHandler.PrintHelpAsync(proxyOutputDevice, toolsInformation); } return new InformativeCommandLineTestHost(0, serviceProvider); @@ -382,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); } @@ -417,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()); @@ -832,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); @@ -844,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/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/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 3c13dcc4a2e..d3e09c4e8b9 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,15 +16,21 @@ public void SetPlatformOutputDevice(Func BuildAsync(ServiceProvider serviceProvider, bool useServerModeOutputDevice) { - 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 nonServerOutputDevice = _platformOutputDeviceFactory is null + ? 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()) { - IPlatformOutputDevice platformOutputDevice = _platformOutputDeviceFactory(serviceProvider); - return platformOutputDevice; + nonServerOutputDevice = GetDefaultTerminalOutputDevice(serviceProvider); } - return GetDefaultTerminalOutputDevice(serviceProvider); + return new ProxyOutputDevice(nonServerOutputDevice, useServerModeOutputDevice ? new ServerModePerCallOutputDevice(serviceProvider) : null); } public static TerminalOutputDevice GetDefaultTerminalOutputDevice(ServiceProvider serviceProvider) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs new file mode 100644 index 00000000000..6896debd84a --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs @@ -0,0 +1,65 @@ +// 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.Hosts; +using Microsoft.Testing.Platform.ServerMode; + +namespace Microsoft.Testing.Platform.OutputDevice; + +internal sealed class ProxyOutputDevice : IOutputDevice +{ + private readonly ServerModePerCallOutputDevice? _serverModeOutputDevice; + + public ProxyOutputDevice(IPlatformOutputDevice originalOutputDevice, ServerModePerCallOutputDevice? serverModeOutputDevice) + { + OriginalOutputDevice = originalOutputDevice; + _serverModeOutputDevice = serverModeOutputDevice; + } + + internal IPlatformOutputDevice OriginalOutputDevice { get; } + + public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) + { + await OriginalOutputDevice.DisplayAsync(producer, data); + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.DisplayAsync(producer, data); + } + } + + internal async Task DisplayBannerAsync(string? bannerMessage) + { + await OriginalOutputDevice.DisplayBannerAsync(bannerMessage); + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.DisplayBannerAsync(bannerMessage); + } + } + + internal async Task DisplayBeforeSessionStartAsync() + { + await OriginalOutputDevice.DisplayBeforeSessionStartAsync(); + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.DisplayBeforeSessionStartAsync(); + } + } + + internal async Task DisplayAfterSessionEndRunAsync() + { + await OriginalOutputDevice.DisplayAfterSessionEndRunAsync(); + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); + } + } + + internal async Task InitializeAsync(ServerTestHost serverTestHost) + { + if (_serverModeOutputDevice is not null) + { + await _serverModeOutputDevice.InitializeAsync(serverTestHost); + } + } +} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 5bd7f79c1a5..3ae6c7d53f7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -671,4 +671,27 @@ 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. + + + 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 + + + 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 fcbdab68b94..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 @@ -271,6 +276,11 @@ selhalo s {0} upozorněním(i). + + Finished test session. + Finished test session. + + For test Pro testování @@ -633,6 +643,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}. @@ -688,6 +708,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ý. @@ -897,6 +927,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 154d7a643b3..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 @@ -271,6 +276,11 @@ fehlerhaft mit {0} Warnung(en) + + Finished test session. + Finished test session. + + For test Für Test @@ -633,6 +643,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. @@ -688,6 +708,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 @@ -897,6 +927,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 ffc6cc03283..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 @@ -271,6 +276,11 @@ error con {0} advertencias + + Finished test session. + Finished test session. + + For test Para prueba @@ -633,6 +643,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}' @@ -688,6 +708,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" @@ -897,6 +927,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 cd2f8e18d62..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 @@ -271,6 +276,11 @@ a échoué avec {0} avertissement(s) + + Finished test session. + Finished test session. + + For test Pour le test @@ -633,6 +643,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 @@ -688,6 +708,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 @@ -897,6 +927,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 9f2e5fd171a..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 @@ -271,6 +276,11 @@ non riuscito con {0} avvisi + + Finished test session. + Finished test session. + + For test Per test @@ -633,6 +643,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}' @@ -688,6 +708,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' @@ -897,6 +927,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 d506fc0e506..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 終了コード @@ -271,6 +276,11 @@ {0} 件の警告付きで失敗しました + + Finished test session. + Finished test session. + + For test テスト用 @@ -634,6 +644,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}' 型のサービスが見つかりません @@ -689,6 +709,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' ファクトリは既に設定されています @@ -898,6 +928,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 9c15b13c2d2..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 종료 코드 @@ -271,6 +276,11 @@ {0} 경고와 함께 실패 + + Finished test session. + Finished test session. + + For test 테스트용 @@ -633,6 +643,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}' 형식의 서비스를 찾을 수 없습니다. @@ -688,6 +708,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' 팩터리가 이미 설정되어 있음 @@ -897,6 +927,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 b8e6cb922e3..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 @@ -271,6 +276,11 @@ zakończono niepowodzeniem, z ostrzeżeniami w liczbie: {0} + + Finished test session. + Finished test session. + + For test Na potrzeby testu @@ -633,6 +643,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}” @@ -688,6 +708,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 @@ -897,6 +927,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 1f4c3e9aebc..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 @@ -271,6 +276,11 @@ falhou com {0} aviso(s) + + Finished test session. + Finished test session. + + For test Para teste @@ -633,6 +643,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}" @@ -688,6 +708,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 @@ -897,6 +927,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 48d7556f60c..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 Код завершения @@ -271,6 +276,11 @@ сбой с предупреждениями ({0}) + + Finished test session. + Finished test session. + + For test Для тестирования @@ -633,6 +643,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}" @@ -688,6 +708,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 уже настроена @@ -897,6 +927,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 6c74b00cf7d..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 @@ -271,6 +276,11 @@ {0} uyarıyla başarısız oldu + + Finished test session. + Finished test session. + + For test Test için @@ -633,6 +643,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 @@ -688,6 +708,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ış @@ -897,6 +927,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 35c5ef5311b..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 退出代码 @@ -271,6 +276,11 @@ 失败,出现 {0} 警告 + + Finished test session. + Finished test session. + + For test 用于测试 @@ -633,6 +643,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}”类型的服务 @@ -688,6 +708,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”工厂 @@ -897,6 +927,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 b9b18bdbaa8..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 結束代碼 @@ -271,6 +276,11 @@ 失敗,有 {0} 個警告 + + Finished test session. + Finished test session. + + For test 用於測試 @@ -633,6 +643,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}' 的服務 @@ -688,6 +708,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' 中心 @@ -897,6 +927,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/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 46f26549e28..091f782ad38 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -1,14 +1,52 @@ // 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.Collections.Concurrent; +using System.Globalization; +using System.Text; + 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; +using Microsoft.Testing.Platform.Resources; +using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.ServerMode; -internal class ServerModePerCallOutputDevice : IPlatformOutputDevice +internal sealed class ServerModePerCallOutputDevice : IPlatformOutputDevice { + private readonly IServiceProvider _serviceProvider; + private readonly ConcurrentBag _messages = new(); + + private IServerTestHost? _serverTestHost; + + private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + + public ServerModePerCallOutputDevice(IServiceProvider serviceProvider) + => _serviceProvider = 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) + { + await LogAsync(message); + } + + _messages.Clear(); + } + public string Uid => nameof(ServerModePerCallOutputDevice); public string Version => AppVersion.DefaultSemVer; @@ -17,13 +55,98 @@ internal class ServerModePerCallOutputDevice : IPlatformOutputDevice public string Description => nameof(ServerModePerCallOutputDevice); - public Task DisplayAfterSessionEndRunAsync() => Task.CompletedTask; + public async Task DisplayAfterSessionEndRunAsync() + => await LogAsync(LogLevel.Trace, PlatformResources.FinishedTestSession, padding: null); + + public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) + { + switch (data) + { + case FormattedTextOutputDeviceData formattedTextOutputDeviceData: + 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; + } + } + + public async Task DisplayBannerAsync(string? bannerMessage) + { + if (bannerMessage is not null) + { + await LogAsync(LogLevel.Debug, bannerMessage, padding: null); + } + } + + public async Task DisplayBeforeSessionStartAsync() + { + if (_serviceProvider.GetService() is { FileLogger.FileName: { } logFileName }) + { + await LogAsync(LogLevel.Trace, string.Format(CultureInfo.InvariantCulture, PlatformResources.StartingTestSessionWithLogFilePath, logFileName), padding: null); + } + else + { + await LogAsync(LogLevel.Trace, PlatformResources.StartingTestSession, padding: null); + } + } + + 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) + { + 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(); + if (paddingValue == 0) + { + return message; + } - public Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) => Task.CompletedTask; + string indent = new(' ', paddingValue); - public Task DisplayBannerAsync(string? bannerMessage) => Task.CompletedTask; + if (!message.Contains('\n')) + { + return indent + message; + } - public Task DisplayBeforeSessionStartAsync() => Task.CompletedTask; + string[] lines = message.Split(NewLineStrings, StringSplitOptions.None); + StringBuilder builder = new(); + foreach (string line in lines) + { + builder.Append(indent); + builder.AppendLine(line); + } - public Task IsEnabledAsync() => Task.FromResult(false); + return builder.ToString(); + } } 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..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 @@ -1,4 +1,4 @@ - + $(NetCurrent) @@ -11,7 +11,10 @@ + + + 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..fc136a29584 --- /dev/null +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -0,0 +1,178 @@ +// 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 partial 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 = 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 '{{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 } + 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(); + } +} +"""; + } + + [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(); +} 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)); - } -}