diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs new file mode 100644 index 0000000000..cd057bc2e9 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.OutputDevice.Terminal; + +internal class ExceptionFlattener +{ + internal static FlatException[] Flatten(string? errorMessage, Exception? exception) + { + if (errorMessage is null && exception is null) + { + return Array.Empty(); + } + + List exceptions = new(); + + string? message = !RoslynString.IsNullOrWhiteSpace(errorMessage) ? errorMessage : exception?.Message; + string? type = exception?.GetType().FullName; + string? stackTrace = exception?.StackTrace; + var flatException = new FlatException(message, type, stackTrace); + + List flatExceptions = new() + { + flatException, + }; + + // Add all inner exceptions. This will flatten top level AggregateExceptions, + // and all AggregateExceptions that are directly in AggregateExceptions, but won't expand + // AggregateExceptions that are in non-aggregate exception inner exceptions. + IEnumerable aggregateExceptions = exception switch + { + AggregateException aggregate => aggregate.Flatten().InnerExceptions, + _ => [exception?.InnerException], + }; + + foreach (Exception? aggregate in aggregateExceptions) + { + Exception? currentException = aggregate; + while (currentException is not null) + { + flatExceptions.Add(new FlatException( + aggregate?.Message, + aggregate?.GetType().FullName, + aggregate?.StackTrace)); + + currentException = currentException.InnerException; + } + } + + return flatExceptions.ToArray(); + } +} + +internal record FlatException(string? ErrorMessage, string? ErrorType, string? StackTrace); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 1b410e5565..afcc850879 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -39,7 +39,7 @@ internal sealed partial class TerminalTestReporter : IDisposable private readonly TestProgressStateAwareTerminal _terminalWithProgress; private readonly uint? _originalConsoleMode; - + private bool _isDiscovery; private DateTimeOffset? _testExecutionStartTime; private DateTimeOffset? _testExecutionEndTime; @@ -132,8 +132,9 @@ internal TerminalTestReporter(IConsole console, TerminalTestReporterOptions opti _terminalWithProgress = terminalWithProgress; } - public void TestExecutionStarted(DateTimeOffset testStartTime, int workerCount) + public void TestExecutionStarted(DateTimeOffset testStartTime, int workerCount, bool isDiscovery) { + _isDiscovery = isDiscovery; _testExecutionStartTime = testStartTime; _terminalWithProgress.StartShowingProgress(workerCount); } @@ -144,7 +145,7 @@ public void AssemblyRunStarted(string assembly, string? targetFramework, string? { _terminalWithProgress.WriteToTerminal(terminal => { - terminal.Append(PlatformResources.RunningTestsFrom); + terminal.Append(_isDiscovery ? PlatformResources.DiscoveringTestsFrom : PlatformResources.RunningTestsFrom); terminal.Append(' '); AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly, targetFramework, architecture); terminal.AppendLine(); @@ -177,7 +178,7 @@ internal void TestExecutionCompleted(DateTimeOffset endTime) _testExecutionEndTime = endTime; _terminalWithProgress.StopShowingProgress(); - _terminalWithProgress.WriteToTerminal(AppendTestRunSummary); + _terminalWithProgress.WriteToTerminal(_isDiscovery ? AppendTestDiscoverySummary : AppendTestRunSummary); NativeMethods.RestoreConsoleMode(_originalConsoleMode); _assemblies.Clear(); @@ -268,6 +269,7 @@ private void AppendTestRunSummary(ITerminal terminal) { terminal.Append(SingleIndentation); AppendAssemblySummary(assemblyRun, terminal); + terminal.AppendLine(); } terminal.AppendLine(); @@ -365,6 +367,37 @@ private static void AppendAssemblyResult(ITerminal terminal, bool succeeded, int } } + internal void TestCompleted( + string assembly, + string? targetFramework, + string? architecture, + string? executionId, + string displayName, + TestOutcome outcome, + TimeSpan duration, + string? errorMessage, + Exception? exception, + string? expected, + string? actual, + string? standardOutput, + string? errorOutput) + { + FlatException[] flatExceptions = ExceptionFlattener.Flatten(errorMessage, exception); + TestCompleted( + assembly, + targetFramework, + architecture, + executionId, + displayName, + outcome, + duration, + flatExceptions, + expected, + actual, + standardOutput, + errorOutput); + } + internal void TestCompleted( string assembly, string? targetFramework, @@ -373,8 +406,7 @@ internal void TestCompleted( string displayName, TestOutcome outcome, TimeSpan duration, - string? errorMessage, - Exception? exception, + FlatException[] exceptions, string? expected, string? actual, string? standardOutput, @@ -412,8 +444,7 @@ internal void TestCompleted( displayName, outcome, duration, - errorMessage, - exception, + exceptions, expected, actual, standardOutput, @@ -435,8 +466,7 @@ private bool GetShowPassedTests() string displayName, TestOutcome outcome, TimeSpan duration, - string? errorMessage, - Exception? exception, + FlatException[] flatExceptions, string? expected, string? actual, string? standardOutput, @@ -482,64 +512,62 @@ private bool GetShowPassedTests() terminal.AppendLine(); - FormatErrorMessage(terminal, errorMessage, exception, outcome); + FormatErrorMessage(terminal, flatExceptions, outcome, 0); FormatExpectedAndActual(terminal, expected, actual); - FormatStackTrace(terminal, exception); - FormatInnerExceptions(terminal, exception); + FormatStackTrace(terminal, flatExceptions, 0); + FormatInnerExceptions(terminal, flatExceptions); FormatStandardAndErrorOutput(terminal, standardOutput, errorOutput); } - private static void FormatInnerExceptions(ITerminal terminal, Exception? exception) + private static void FormatInnerExceptions(ITerminal terminal, FlatException[] exceptions) { - IEnumerable aggregateExceptions = exception switch + if (exceptions is null || exceptions.Length == 0) { - AggregateException aggregate => aggregate.Flatten().InnerExceptions, - _ => [exception?.InnerException], - }; + return; + } - foreach (Exception? aggregate in aggregateExceptions) + for (int i = 1; i < exceptions.Length; i++) { - Exception? currentException = aggregate; - while (currentException is not null) - { - terminal.SetColor(TerminalColor.Red); - terminal.Append(SingleIndentation); - terminal.Append("--->"); - FormatErrorMessage(terminal, null, currentException, TestOutcome.Error); - - FormatStackTrace(terminal, currentException); - - currentException = currentException.InnerException; - } + terminal.SetColor(TerminalColor.Red); + terminal.Append(SingleIndentation); + terminal.Append("--->"); + FormatErrorMessage(terminal, exceptions, TestOutcome.Error, i); + FormatStackTrace(terminal, exceptions, i); } } - private static void FormatErrorMessage(ITerminal terminal, string? errorMessage, Exception? exception, TestOutcome outcome) + private static void FormatErrorMessage(ITerminal terminal, FlatException[] exceptions, TestOutcome outcome, int index) { - if (RoslynString.IsNullOrWhiteSpace(errorMessage) && exception is null) + string? firstErrorMessage = GetStringFromIndexOrDefault(exceptions, e => e.ErrorMessage, index); + string? firstErrorType = GetStringFromIndexOrDefault(exceptions, e => e.ErrorType, index); + string? firstStackTrace = GetStringFromIndexOrDefault(exceptions, e => e.StackTrace, index); + if (RoslynString.IsNullOrWhiteSpace(firstErrorMessage) && RoslynString.IsNullOrWhiteSpace(firstErrorType) && RoslynString.IsNullOrWhiteSpace(firstStackTrace)) { return; } terminal.SetColor(TerminalColor.Red); - if (exception is null) + if (firstStackTrace is null) { - AppendIndentedLine(terminal, errorMessage, SingleIndentation); + AppendIndentedLine(terminal, firstErrorMessage, SingleIndentation); } else if (outcome == TestOutcome.Fail) { // For failed tests, we don't prefix the message with the exception type because it is most likely an assertion specific exception like AssertionFailedException, and we prefer to show that without the exception type to avoid additional noise. - AppendIndentedLine(terminal, errorMessage ?? exception.Message, SingleIndentation); + AppendIndentedLine(terminal, firstErrorMessage, SingleIndentation); } else { - AppendIndentedLine(terminal, $"{exception.GetType().FullName}: {errorMessage ?? exception.Message}", SingleIndentation); + AppendIndentedLine(terminal, $"{firstErrorType}: {firstErrorMessage}", SingleIndentation); } terminal.ResetColor(); } + private static string? GetStringFromIndexOrDefault(FlatException[] exceptions, Func property, int index) => + exceptions != null && exceptions.Length >= index + 1 ? property(exceptions[index]) : null; + private static void FormatExpectedAndActual(ITerminal terminal, string? expected, string? actual) { if (RoslynString.IsNullOrWhiteSpace(expected) && RoslynString.IsNullOrWhiteSpace(actual)) @@ -557,9 +585,10 @@ private static void FormatExpectedAndActual(ITerminal terminal, string? expected terminal.ResetColor(); } - private static void FormatStackTrace(ITerminal terminal, Exception? exception) + private static void FormatStackTrace(ITerminal terminal, FlatException[] exceptions, int index) { - if (exception?.StackTrace is not { } stackTrace) + string? stackTrace = GetStringFromIndexOrDefault(exceptions, e => e.StackTrace, index); + if (RoslynString.IsNullOrWhiteSpace(stackTrace)) { return; } @@ -684,17 +713,46 @@ private static void AppendIndentedLine(ITerminal terminal, string? message, stri } } - internal void AssemblyRunCompleted(string assembly, string? targetFramework, string? architecture, string? executionId) + internal void AssemblyRunCompleted(string assembly, string? targetFramework, string? architecture, string? executionId, + // These parameters are useful only for "remote" runs in dotnet test, where we are reporting on multiple processes. + // In single process run, like with testing platform .exe we report these via messages, and run exit. + int? exitCode, string? outputData, string? errorData) { TestProgressState assemblyRun = GetOrAddAssemblyRun(assembly, targetFramework, architecture, executionId); assemblyRun.Stopwatch.Stop(); _terminalWithProgress.RemoveWorker(assemblyRun.SlotIndex); - if (_options.ShowAssembly && _options.ShowAssemblyStartAndComplete) + if (!_isDiscovery && _options.ShowAssembly && _options.ShowAssemblyStartAndComplete) { _terminalWithProgress.WriteToTerminal(terminal => AppendAssemblySummary(assemblyRun, terminal)); } + + if (exitCode is null or 0) + { + // Report nothing, we don't want to report on success, because then we will also report on test-discovery etc. + return; + } + + _terminalWithProgress.WriteToTerminal(terminal => + { + AppendExecutableSummary(terminal, exitCode, outputData, errorData); + terminal.AppendLine(); + }); + } + + private static void AppendExecutableSummary(ITerminal terminal, int? exitCode, string? outputData, string? errorData) + { + terminal.AppendLine(); + terminal.Append(PlatformResources.ExitCode); + terminal.Append(": "); + terminal.AppendLine(exitCode?.ToString(CultureInfo.CurrentCulture) ?? ""); + terminal.Append(PlatformResources.StandardOutput); + terminal.AppendLine(":"); + terminal.AppendLine(RoslynString.IsNullOrWhiteSpace(outputData) ? string.Empty : outputData); + terminal.Append(PlatformResources.StandardError); + terminal.AppendLine(":"); + terminal.AppendLine(RoslynString.IsNullOrWhiteSpace(errorData) ? string.Empty : errorData); } private static string? NormalizeSpecialCharacters(string? text) @@ -712,7 +770,6 @@ private static void AppendAssemblySummary(TestProgressState assemblyRun, ITermin AppendAssemblyResult(terminal, assemblyRun.FailedTests == 0, failedTests, warnings); terminal.Append(' '); AppendLongDuration(terminal, assemblyRun.Stopwatch.Elapsed); - terminal.AppendLine(); } /// @@ -831,6 +888,73 @@ internal void WriteMessage(string text, SystemConsoleColor? color = null, int? p } } + internal void TestDiscovered( + string assembly, + string? targetFramework, + string? architecture, + string? executionId, + string? displayName, + string? uid) + { + TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}|{executionId}"]; + + // TODO: add mode for discovered tests to the progress bar - jajares + asm.PassedTests++; + asm.TotalTests++; + asm.DiscoveredTests.Add(new(displayName, uid)); + _terminalWithProgress.UpdateWorker(asm.SlotIndex); + } + + public void AppendTestDiscoverySummary(ITerminal terminal) + { + terminal.AppendLine(); + + var assemblies = _assemblies.Select(asm => asm.Value).OrderBy(a => a.Assembly).Where(a => a is not null).ToList(); + + int totalTests = _assemblies.Values.Sum(a => a.TotalTests); + bool runFailed = _wasCancelled; + + foreach (TestProgressState assembly in assemblies) + { + terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiscoveredTestsInAssembly, assembly.DiscoveredTests.Count)); + terminal.Append(" - "); + AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly.Assembly, assembly.TargetFramework, assembly.Architecture); + terminal.AppendLine(); + foreach ((string? displayName, string? uid) in assembly.DiscoveredTests) + { + if (displayName is not null) + { + terminal.Append(SingleIndentation); + terminal.AppendLine(displayName); + } + } + + terminal.AppendLine(); + } + + terminal.SetColor(runFailed ? TerminalColor.Red : TerminalColor.Green); + if (assemblies.Count <= 1) + { + terminal.AppendLine(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummarySingular, totalTests)); + } + else + { + terminal.AppendLine(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummary, totalTests, assemblies.Count)); + } + + terminal.ResetColor(); + terminal.AppendLine(); + + if (_wasCancelled) + { + terminal.Append(PlatformResources.Aborted); + terminal.AppendLine(); + } + } + + public void AssemblyDiscoveryCompleted(int testCount) => + _terminalWithProgress.WriteToTerminal(terminal => terminal.Append($"Found {testCount} tests")); + private static TerminalColor ToTerminalColor(ConsoleColor consoleColor) => consoleColor switch { diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index 7ea23e1b32..d117e2df4f 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -44,6 +44,8 @@ public TestProgressState(string assembly, string? targetFramework, string? archi public long LastUpdate { get; internal set; } + public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = new(); + internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index c11ce3e40f..a0601b4491 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -287,7 +287,7 @@ public async Task DisplayBeforeSessionStartAsync() // Start test execution here, rather than in ShowBanner, because then we know // if we are a testHost controller or not, and if we should show progress bar. - _terminalTestReporter.TestExecutionStarted(_clock.UtcNow, workerCount: 1); + _terminalTestReporter.TestExecutionStarted(_clock.UtcNow, workerCount: 1, isDiscovery: false); _terminalTestReporter.AssemblyRunStarted(_assemblyName, _targetFramework, _shortArchitecture, executionId: null); if (_logger is not null && _logger.IsEnabled(LogLevel.Trace)) { @@ -323,7 +323,7 @@ private async Task DisplayAfterSessionEndRunInternalAsync() { if (!_firstCallTo_OnSessionStartingAsync) { - _terminalTestReporter.AssemblyRunCompleted(_assemblyName, _targetFramework, _shortArchitecture, executionId: null); + _terminalTestReporter.AssemblyRunCompleted(_assemblyName, _targetFramework, _shortArchitecture, executionId: null, exitCode: null, outputData: null, errorData: null); _terminalTestReporter.TestExecutionCompleted(_clock.UtcNow); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index f1147eec56..9128ec9304 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -567,7 +567,7 @@ Read more about Microsoft Testing Platform telemetry: https://aka.ms/testingplat Exception that is thrown when console is already collecting input into a batch (into a string builder), and code asks to enable batching mode again. - failed with {0} errors(s) + failed with {0} error(s) failed with {0} error(s) and {1} warning(s) @@ -637,4 +637,22 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Standard output - \ No newline at end of file + + Discovering tests from + + + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovered {0} tests. + 0 is number of tests + + + Exit code + + 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 9fc1b0795e..23b185297c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Zprostředkovatel {0} (UID: {1}) selhal s chybou: {2}. + + Exit code + Exit code + + Expected Očekáváno @@ -227,8 +242,8 @@ - failed with {0} errors(s) - selhalo s chybami ({0}) + failed with {0} error(s) + selhalo s chybami ({0}) @@ -745,6 +760,16 @@ Platné hodnoty jsou Normal a Detailed. Výchozí hodnota je Normal. Režim VSTest podporuje jen jeden TestApplicationBuilder na proces. + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object Pro tento objekt proxy neměla být volána metoda {0}. 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 bbd8c562a8..80a464802d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Anbieter "{0}" (UID: {1}) ist mit folgendem Fehler fehlgeschlagen: {2} + + Exit code + Exit code + + Expected Erwartet @@ -227,8 +242,8 @@ - failed with {0} errors(s) - Fehlgeschlagen mit {0} Fehler(n) + failed with {0} error(s) + Fehlgeschlagen mit {0} Fehler(n) @@ -745,6 +760,16 @@ Gültige Werte sind „Normal“, „Detailed“. Der Standardwert ist „Normal Der VSTest-Modus unterstützt nur einen einzelnen TestApplicationBuilder pro Prozess. + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object Die Methode "{0}" hätte für dieses Proxyobjekt nicht aufgerufen werden dürfen 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 95546248c8..d63cdde2ae 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Error del proveedor "{0}" (UID: {1}) con el error: {2} + + Exit code + Exit code + + Expected Se esperaba @@ -227,8 +242,8 @@ - failed with {0} errors(s) - error con {0} errores + failed with {0} error(s) + error con {0} errores @@ -745,6 +760,16 @@ Los valores válidos son 'Normal', 'Detallado'. El valor predeterminado es 'Norm El modo VSTest solo admite un único TestApplicationBuilder por proceso + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object No se debería haber llamado al método "{0}" en este objeto proxy 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 7900295069..645a536c54 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Désolé, échec de l’« {0} » du fournisseur (UID : {1}) avec l’erreur : {2} + + Exit code + Exit code + + Expected Attendu @@ -227,8 +242,8 @@ - failed with {0} errors(s) - Désolé... Nous avons rencontré {0} erreur(s) + failed with {0} error(s) + Désolé... Nous avons rencontré {0} erreur(s) @@ -745,6 +760,16 @@ Les valeurs valides sont « Normal » et « Détaillé ». La valeur par dé Le mode VSTest ne prend en charge qu’un seul TestApplicationBuilder par processus + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object La méthode « {0} » n’aurait pas dû être appelée sur cet objet proxy 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 0b79c71f8c..3a14e5aed1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Provider '{0}' (UID: {1}) non riuscito con errore: {2} + + Exit code + Exit code + + Expected Previsto @@ -227,8 +242,8 @@ - failed with {0} errors(s) - non riuscito con {0} errori + failed with {0} error(s) + non riuscito con {0} errori @@ -745,6 +760,16 @@ I valori validi sono 'Normal', 'Detailed'. L'impostazione predefinita è 'Normal La modalità VSTest supporta solo un singolo TestApplicationBuilder per processo + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object Il metodo '{0}' non avrebbe dovuto essere chiamato su questo oggetto proxy 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 e89928ad20..2b9e9432ac 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} プロバイダー '{0}' (UID: {1}) が次のエラーで失敗しました: {2} + + Exit code + Exit code + + Expected 予想 @@ -227,8 +242,8 @@ - failed with {0} errors(s) - {0} エラーで失敗しました + failed with {0} error(s) + {0} エラーで失敗しました @@ -746,6 +761,16 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. VSTest モードは、プロセスごとに 1 つの TestApplicationBuilder のみをサポートします + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object このプロキシ オブジェクトでメソッド '{0}' を呼び出すべきではありませんでした 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 2e7b4dff22..68036a8735 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} 공급자 '{0}'(UID: {1})이 오류 {2}(으)로 실패했습니다. + + Exit code + Exit code + + Expected 필요 @@ -227,8 +242,8 @@ - failed with {0} errors(s) - {0} 오류와 함께 실패 + failed with {0} error(s) + {0} 오류와 함께 실패 @@ -745,6 +760,16 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. VSTest 모드는 프로세스당 단일 TestApplicationBuilder만 지원합니다. + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object 이 프록시 개체에서 '{0}' 메서드를 호출하지 않아야 합니다. 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 52085f2dea..62d3f1fed7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Dostawca „{0}” (UID:{1}) nie powiódł się z powodu błędu: {2} + + Exit code + Exit code + + Expected Oczekiwane @@ -227,8 +242,8 @@ - failed with {0} errors(s) - zakończono niepowodzeniem z następującą liczbą błędów: {0} + failed with {0} error(s) + zakończono niepowodzeniem z następującą liczbą błędów: {0} @@ -745,6 +760,16 @@ Prawidłowe wartości to „Normalne”, „Szczegółowe”. Wartość domyśln Tryb VSTest obsługuje tylko jeden element TestApplicationBuilder na proces + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object Metoda „{0}” nie powinna być wywoływana w tym obiekcie proxy 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 3565d6a5d3..de1cfb38a6 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 @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} O provedor ''{0}'' (UID: {1}) falhou com o erro: {2} + + Exit code + Exit code + + Expected Esperado @@ -227,8 +242,8 @@ - failed with {0} errors(s) - falhou com {0} erro(s) + failed with {0} error(s) + falhou com {0} erro(s) @@ -745,6 +760,16 @@ Os valores válidos são “Normal”, “Detalhado”. O padrão é “Normal O modo VSTest dá suporte apenas a um único TestApplicationBuilder por processo + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object O método ''{0}'' não deve ter sido chamado neste objeto proxy 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 b45cc4b447..6b6b3c52fb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} Сбой поставщика "{0}" (ИД пользователя: {1}) с ошибкой: {2} + + Exit code + Exit code + + Expected Ожидалось @@ -227,8 +242,8 @@ - failed with {0} errors(s) - сбой с ошибками {0} + failed with {0} error(s) + сбой с ошибками {0} @@ -745,6 +760,16 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. Режим VSTest поддерживает только один TestApplicationBuilder для каждого процесса + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object Метод "{0}" не должен был вызываться для этого прокси-объекта 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 f9206213f2..67f31c148a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} '{0}' sağlayıcısı '' (UID: {1}) şu hatayla başarısız oldu: {2} + + Exit code + Exit code + + Expected Beklenen @@ -227,8 +242,8 @@ - failed with {0} errors(s) - {0} hatayla başarısız oldu + failed with {0} error(s) + {0} hatayla başarısız oldu @@ -745,6 +760,16 @@ Geçerli değerler: ‘Normal’, ‘Ayrıntılı’. Varsayılan değer: ‘Nor VSTest modu, işlem başına yalnızca tek bir TestApplicationBuilder destekler + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object '{0}' yöntemi bu ara sunucu nesnesinde çağrılmamalıdır 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 1d8b1a6f4b..03a643fe00 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 @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} 提供程序 '{0}' (UID: {1}) 失败,出现错误: {2} + + Exit code + Exit code + + Expected 预期 @@ -227,8 +242,8 @@ - failed with {0} errors(s) - 失败,出现 {0} 个错误 + failed with {0} error(s) + 失败,出现 {0} 个错误 @@ -745,6 +760,16 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. VSTest 模式仅支持每个进程一个 TestApplicationBuilder + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object 不应对此代理对象调用方法 '{0}' 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 906a5849e0..6610d74ffa 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 @@ -189,11 +189,26 @@ 0 level such as verbose, 1 path to file + + Discovered {0} tests in assembly + Discovered {0} tests in assembly + 0 is count, the sentence is followed by the path of the assebly + + + Discovering tests from + Discovering tests from + + Provider '{0}' (UID: {1}) failed with error: {2} 提供者 '{0}' (UID: {1}) 失敗,發生錯誤: {2} + + Exit code + Exit code + + Expected 預期 @@ -227,8 +242,8 @@ - failed with {0} errors(s) - 失敗,發生 {0} 個錯誤 + failed with {0} error(s) + 失敗,發生 {0} 個錯誤 @@ -745,6 +760,16 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. VSTest 模式僅支援每一程序的單一 TestApplicationBuilder + + Discovered {0} tests in {1} assemblies. + Discovered {0} tests in {1} assemblies. + 0 is number of tests, 1 is count of assemblies + + + Discovered {0} tests. + Discovered {0} tests. + 0 is number of tests + Method '{0}' should not have been called on this proxy object 不應在此 Proxy 物件上呼叫方法 '{0}'。 diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index 2a0573a6ab..63af8f949c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -4,6 +4,7 @@ using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.IPC.Models; +using Microsoft.Testing.Platform.OutputDevice.Terminal; using Microsoft.Testing.Platform.ServerMode; using Microsoft.Testing.Platform.TestHost; @@ -35,7 +36,7 @@ public DotnetTestDataConsumer(DotnetTestConnection dotnetTestConnection, IEnviro public string DisplayName => nameof(DotnetTestDataConsumer); - public string Description => "Send back information to the dotnet test"; + public string Description => "Send information back to the dotnet test"; private string? ExecutionId => _environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID); @@ -100,8 +101,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeDetails.State, testNodeDetails.Duration, testNodeDetails.Reason ?? string.Empty, - testNodeDetails.ErrorMessage ?? string.Empty, - testNodeDetails.ErrorStackTrace ?? string.Empty, + testNodeDetails.Exceptions, testNodeDetails.StandardOutput ?? string.Empty, testNodeDetails.StandardError ?? string.Empty, testNodeUpdateMessage.SessionUid.Value), @@ -171,7 +171,7 @@ private static TestNodeDetails GetTestNodeDetails(TestNodeUpdateMessage testNode byte? state = null; long? duration = null; string? reason = string.Empty; - string? errorMessage = string.Empty; + ExceptionMessage[]? exceptions = null; string? errorStackTrace = string.Empty; TestNodeStateProperty nodeState = testNodeUpdateMessage.TestNode.Properties.Single(); @@ -199,39 +199,53 @@ private static TestNodeDetails GetTestNodeDetails(TestNodeUpdateMessage testNode state = TestStates.Failed; duration = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault()?.GlobalTiming.Duration.Ticks; reason = nodeState.Explanation; - errorMessage = failedTestNodeStateProperty.Exception?.Message; - errorStackTrace = failedTestNodeStateProperty.Exception?.StackTrace; + exceptions = FlattenToExceptionMessages(reason, failedTestNodeStateProperty.Exception); break; case ErrorTestNodeStateProperty errorTestNodeStateProperty: state = TestStates.Error; duration = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault()?.GlobalTiming.Duration.Ticks; reason = nodeState.Explanation; - errorMessage = errorTestNodeStateProperty.Exception?.Message; - errorStackTrace = errorTestNodeStateProperty.Exception?.StackTrace; + exceptions = FlattenToExceptionMessages(reason, errorTestNodeStateProperty.Exception); break; case TimeoutTestNodeStateProperty timeoutTestNodeStateProperty: state = TestStates.Timeout; duration = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault()?.GlobalTiming.Duration.Ticks; reason = nodeState.Explanation; - errorMessage = timeoutTestNodeStateProperty.Exception?.Message; - errorStackTrace = timeoutTestNodeStateProperty.Exception?.StackTrace; + exceptions = FlattenToExceptionMessages(reason, timeoutTestNodeStateProperty.Exception); break; case CancelledTestNodeStateProperty cancelledTestNodeStateProperty: state = TestStates.Cancelled; duration = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault()?.GlobalTiming.Duration.Ticks; reason = nodeState.Explanation; - errorMessage = cancelledTestNodeStateProperty.Exception?.Message; - errorStackTrace = cancelledTestNodeStateProperty.Exception?.StackTrace; + exceptions = FlattenToExceptionMessages(reason, cancelledTestNodeStateProperty.Exception); break; } - return new TestNodeDetails(state, duration, reason, errorMessage, errorStackTrace, standardOutput, standardError); + return new TestNodeDetails(state, duration, reason, exceptions, standardOutput, standardError); + + static ExceptionMessage[]? FlattenToExceptionMessages(string? errorMessage, Exception? exception) + { + if (errorMessage is null && exception is null) + { + return null; + } + + FlatException[] exceptions = ExceptionFlattener.Flatten(errorMessage, exception); + + var exceptionMessages = new ExceptionMessage[exceptions.Length]; + for (int i = 0; i < exceptions.Length; i++) + { + exceptionMessages[i] = new ExceptionMessage(exceptions[i].ErrorMessage, exceptions[i].ErrorType, exceptions[i].StackTrace); + } + + return exceptionMessages; + } } - public record TestNodeDetails(byte? State, long? Duration, string? Reason, string? ErrorMessage, string? ErrorStackTrace, string? StandardOutput, string? StandardError); + public record TestNodeDetails(byte? State, long? Duration, string? Reason, ExceptionMessage[]? Exceptions, string? StandardOutput, string? StandardError); public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs index e7c82a4fac..b7a39406d2 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs @@ -5,6 +5,8 @@ namespace Microsoft.Testing.Platform.IPC.Models; internal sealed record SuccessfulTestResultMessage(string? Uid, string? DisplayName, byte? State, long? Duration, string? Reason, string? StandardOutput, string? ErrorOutput, string? SessionUid); -internal sealed record FailedTestResultMessage(string? Uid, string? DisplayName, byte? State, long? Duration, string? Reason, string? ErrorMessage, string? ErrorStackTrace, string? StandardOutput, string? ErrorOutput, string? SessionUid); +internal sealed record FailedTestResultMessage(string? Uid, string? DisplayName, byte? State, long? Duration, string? Reason, ExceptionMessage[]? Exceptions, string? StandardOutput, string? ErrorOutput, string? SessionUid); internal sealed record TestResultMessages(string? ExecutionId, SuccessfulTestResultMessage[] SuccessfulTestMessages, FailedTestResultMessage[] FailedTestMessages) : IRequest; + +internal sealed record ExceptionMessage(string? ErrorMessage, string? ErrorType, string? StackTrace); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs index e143ef3b06..1cd6e3dd05 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs @@ -80,13 +80,19 @@ internal static class FailedTestResultMessageFieldsId public const ushort State = 3; public const ushort Duration = 4; public const ushort Reason = 5; - public const ushort ErrorMessage = 6; - public const ushort ErrorStackTrace = 7; + public const ushort ExceptionMessageList = 6; public const ushort StandardOutput = 8; public const ushort ErrorOutput = 9; public const ushort SessionUid = 10; } +internal static class ExceptionMessageFieldsId +{ + public const ushort ErrorMessage = 1; + public const ushort ErrorType = 2; + public const ushort StackTrace = 3; +} + internal static class FileArtifactMessagesFieldsId { public const int MessagesSerializerId = 7; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs index 6707272cd7..d62e8cb50b 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs @@ -214,8 +214,8 @@ private static List ReadFailedTestMessagesPayload(Strea int length = ReadInt(stream); for (int i = 0; i < length; i++) { - string? uid = null, displayName = null, reason = null, sessionUid = null, - errorMessage = null, errorStackTrace = null, standardOutput = null, errorOutput = null; + string? uid = null, displayName = null, reason = null, sessionUid = null, standardOutput = null, errorOutput = null; + List exceptionMessages = []; byte? state = null; long? duration = null; @@ -248,13 +248,43 @@ private static List ReadFailedTestMessagesPayload(Strea reason = ReadStringValue(stream, fieldSize); break; - case FailedTestResultMessageFieldsId.ErrorMessage: - errorMessage = ReadStringValue(stream, fieldSize); - break; + case FailedTestResultMessageFieldsId.ExceptionMessageList: + { + int length2 = ReadInt(stream); + for (int k = 0; k < length2; k++) + { + int fieldCount2 = ReadShort(stream); - case FailedTestResultMessageFieldsId.ErrorStackTrace: - errorStackTrace = ReadStringValue(stream, fieldSize); - break; + string? errorMessage = null; + string? errorType = null; + string? stackTrace = null; + + for (int l = 0; l < fieldCount2; l++) + { + int fieldId2 = ReadShort(stream); + int fieldSize2 = ReadInt(stream); + + switch (fieldId2) + { + case ExceptionMessageFieldsId.ErrorMessage: + errorMessage = ReadStringValue(stream, fieldSize2); + break; + + case ExceptionMessageFieldsId.ErrorType: + errorType = ReadStringValue(stream, fieldSize2); + break; + + case ExceptionMessageFieldsId.StackTrace: + stackTrace = ReadStringValue(stream, fieldSize2); + break; + } + } + + exceptionMessages.Add(new ExceptionMessage(errorMessage, errorType, stackTrace)); + } + + break; + } case FailedTestResultMessageFieldsId.StandardOutput: standardOutput = ReadStringValue(stream, fieldSize); @@ -274,7 +304,7 @@ private static List ReadFailedTestMessagesPayload(Strea } } - failedTestResultMessages.Add(new FailedTestResultMessage(uid, displayName, state, duration, reason, errorMessage, errorStackTrace, standardOutput, errorOutput, sessionUid)); + failedTestResultMessages.Add(new FailedTestResultMessage(uid, displayName, state, duration, reason, exceptionMessages.ToArray(), standardOutput, errorOutput, sessionUid)); } return failedTestResultMessages; @@ -351,8 +381,7 @@ private static void WriteFailedTestMessagesPayload(Stream stream, FailedTestResu WriteField(stream, FailedTestResultMessageFieldsId.State, failedTestResultMessage.State); WriteField(stream, FailedTestResultMessageFieldsId.Duration, failedTestResultMessage.Duration); WriteField(stream, FailedTestResultMessageFieldsId.Reason, failedTestResultMessage.Reason); - WriteField(stream, FailedTestResultMessageFieldsId.ErrorMessage, failedTestResultMessage.ErrorMessage); - WriteField(stream, FailedTestResultMessageFieldsId.ErrorStackTrace, failedTestResultMessage.ErrorStackTrace); + WriteExceptionMessagesPayload(stream, failedTestResultMessage.Exceptions); WriteField(stream, FailedTestResultMessageFieldsId.StandardOutput, failedTestResultMessage.StandardOutput); WriteField(stream, FailedTestResultMessageFieldsId.ErrorOutput, failedTestResultMessage.ErrorOutput); WriteField(stream, FailedTestResultMessageFieldsId.SessionUid, failedTestResultMessage.SessionUid); @@ -363,6 +392,35 @@ private static void WriteFailedTestMessagesPayload(Stream stream, FailedTestResu WriteAtPosition(stream, (int)(stream.Position - before), before - sizeof(int)); } + private static void WriteExceptionMessagesPayload(Stream stream, ExceptionMessage[]? exceptionMessages) + { + if (exceptionMessages is null || exceptionMessages.Length == 0) + { + return; + } + + WriteShort(stream, FailedTestResultMessageFieldsId.ExceptionMessageList); + + // We will reserve an int (4 bytes) + // so that we fill the size later, once we write the payload + WriteInt(stream, 0); + + long before = stream.Position; + WriteInt(stream, exceptionMessages.Length); + foreach (ExceptionMessage exceptionMessage in exceptionMessages) + { + WriteShort(stream, GetFieldCount(exceptionMessage)); + + WriteField(stream, ExceptionMessageFieldsId.ErrorMessage, exceptionMessage.ErrorMessage); + WriteField(stream, ExceptionMessageFieldsId.ErrorType, exceptionMessage.ErrorType); + WriteField(stream, ExceptionMessageFieldsId.StackTrace, exceptionMessage.StackTrace); + } + + // NOTE: We are able to seek only if we are using a MemoryStream + // thus, the seek operation is fast as we are only changing the value of a property + WriteAtPosition(stream, (int)(stream.Position - before), before - sizeof(int)); + } + private static ushort GetFieldCount(TestResultMessages testResultMessages) => (ushort)((testResultMessages.ExecutionId is null ? 0 : 1) + (IsNullOrEmpty(testResultMessages.SuccessfulTestMessages) ? 0 : 1) + @@ -384,9 +442,13 @@ private static ushort GetFieldCount(FailedTestResultMessage failedTestResultMess (failedTestResultMessage.State is null ? 0 : 1) + (failedTestResultMessage.Duration is null ? 0 : 1) + (failedTestResultMessage.Reason is null ? 0 : 1) + - (failedTestResultMessage.ErrorMessage is null ? 0 : 1) + - (failedTestResultMessage.ErrorStackTrace is null ? 0 : 1) + + (IsNullOrEmpty(failedTestResultMessage.Exceptions) ? 0 : 1) + (failedTestResultMessage.StandardOutput is null ? 0 : 1) + (failedTestResultMessage.ErrorOutput is null ? 0 : 1) + (failedTestResultMessage.SessionUid is null ? 0 : 1)); + + private static ushort GetFieldCount(ExceptionMessage exceptionMessage) => + (ushort)((exceptionMessage.ErrorMessage is null ? 0 : 1) + + (exceptionMessage.ErrorType is null ? 0 : 1) + + (exceptionMessage.StackTrace is null ? 0 : 1)); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs new file mode 100644 index 0000000000..9928d95bff --- /dev/null +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -0,0 +1,33 @@ +// 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.IPC.Models; +using Microsoft.Testing.Platform.IPC.Serializers; + +namespace Microsoft.Testing.Platform.UnitTests; + +[TestGroup] +public sealed class ProtocolTests : TestBase +{ + public ProtocolTests(ITestExecutionContext testExecutionContext) + : base(testExecutionContext) + { + } + + public void TestResultMessagesSerializeDeserialize() + { + var success = new SuccessfulTestResultMessage("uid", "displayName", 1, 100, "reason", "standardOutput", "errorOutput", "sessionUid"); + var fail = new FailedTestResultMessage("uid", "displayName", 2, 200, "reason", [new ExceptionMessage("errorMessage", "errorType", "stackTrace")], "standardOutput", "errorOutput", "sessionUid"); + var message = new TestResultMessages("executionId", new[] { success }, new[] { fail }); + + var stream = new MemoryStream(); + new TestResultMessagesSerializer().Serialize(message, stream); + stream.Seek(0, SeekOrigin.Begin); + var actual = (TestResultMessages)new TestResultMessagesSerializer().Deserialize(stream); + Assert.AreEqual(message.ExecutionId, actual.ExecutionId); +#if NET8_0_OR_GREATER + Assert.AreEqual(System.Text.Json.JsonSerializer.Serialize(message), System.Text.Json.JsonSerializer.Serialize(actual)); +#endif + Assert.AreEqual(message.FailedTestMessages?[0].Exceptions?[0].ErrorMessage, actual.FailedTestMessages?[0].Exceptions?[0].ErrorMessage); + } +} diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index 266aae61d9..58ad5b0aad 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -58,7 +58,7 @@ public void OutputFormattingIsCorrect() DateTimeOffset startTime = DateTimeOffset.MinValue; DateTimeOffset endTime = DateTimeOffset.MaxValue; - terminalReporter.TestExecutionStarted(startTime, 1); + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); string targetFramework = "net8.0"; string architecture = "x64"; @@ -85,7 +85,7 @@ public void OutputFormattingIsCorrect() errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, executionId: null, testName: null, @$"{folder}artifact1.txt"); terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, executionId: null, testName: null, @$"{folder}artifact2.txt"); - terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, executionId: null); + terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, executionId: null, exitCode: null, outputData: null, errorData: null); terminalReporter.TestExecutionCompleted(endTime); string output = stringBuilderConsole.Output;