diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 8f2f318036..b6279fd059 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -58,3 +58,9 @@ Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.TestNodeDetails.Deconstruc *REMOVED*Microsoft.Testing.Platform.IPC.Models.FailedTestResultMessage.Deconstruct(out string? Uid, out string? DisplayName, out byte? State, out long? Duration, out string? Reason, out Microsoft.Testing.Platform.IPC.Models.ExceptionMessage![]? Exceptions, out string? StandardOutput, out string? ErrorOutput, out string? SessionUid) -> void *REMOVED*Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.TestNodeDetails.TestNodeDetails(byte? State, long? Duration, string? Reason, Microsoft.Testing.Platform.IPC.Models.ExceptionMessage![]? Exceptions, string? StandardOutput, string? StandardError, Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty![]! Artifacts, Microsoft.Testing.Platform.Extensions.Messages.TestMetadataProperty![]! Traits) -> void *REMOVED*Microsoft.Testing.Platform.IPC.DotnetTestDataConsumer.TestNodeDetails.Deconstruct(out byte? State, out long? Duration, out string? Reason, out Microsoft.Testing.Platform.IPC.Models.ExceptionMessage![]? Exceptions, out string? StandardOutput, out string? StandardError, out Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty![]! Artifacts, out Microsoft.Testing.Platform.Extensions.Messages.TestMetadataProperty![]! Traits) -> void +const Microsoft.Testing.Platform.OutputDevice.Terminal.TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption = "show-slowest-tests" -> string! +Microsoft.Testing.Platform.OutputDevice.Terminal.TerminalTestReporterOptions.SlowestTestsCount.get -> int +Microsoft.Testing.Platform.OutputDevice.Terminal.TerminalTestReporterOptions.SlowestTestsCount.init -> void +Microsoft.Testing.Platform.OutputDevice.Terminal.TestProgressState.RecordTestDuration(string! testNodeUid, string! displayName, System.TimeSpan? duration) -> void +Microsoft.Testing.Platform.OutputDevice.Terminal.TestProgressState.GetSlowestTests(int count) -> System.Collections.Generic.IReadOnlyList<(string! DisplayName, System.TimeSpan Duration)>! +static Microsoft.Testing.Platform.OutputDevice.TerminalOutputDevice.GetSlowestTestsCount(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions) -> int diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.cs index 7905c278c0..ebb301ccf8 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.cs @@ -87,6 +87,8 @@ internal static partial class TerminalResources internal static string @SkippedLowercase => GetResourceString("SkippedLowercase"); + internal static string @SlowestTests => GetResourceString("SlowestTests"); + internal static string @StackFrameAt => GetResourceString("StackFrameAt"); internal static string @StackFrameIn => GetResourceString("StackFrameIn"); @@ -121,6 +123,10 @@ internal static partial class TerminalResources internal static string @TerminalShowOutputOptionInvalidArgument => GetResourceString("TerminalShowOutputOptionInvalidArgument"); + internal static string @TerminalShowSlowestTestsOptionDescription => GetResourceString("TerminalShowSlowestTestsOptionDescription"); + + internal static string @TerminalShowSlowestTestsOptionInvalidArgument => GetResourceString("TerminalShowSlowestTestsOptionInvalidArgument"); + internal static string @TerminalShowStderrOptionDescription => GetResourceString("TerminalShowStderrOptionDescription"); internal static string @TerminalShowStdoutOptionDescription => GetResourceString("TerminalShowStdoutOptionDescription"); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.resx b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.resx index af81784291..67a4ea771a 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalResources.resx @@ -165,6 +165,9 @@ skipped + + Slowest tests: + total @@ -259,6 +262,13 @@ Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an --show-stdout and --show-stderr expect a single parameter with value 'All', 'Failed', or 'None'. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Error output diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.Summary.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.Summary.cs index b03abc643e..d072485aa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.Summary.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.Summary.cs @@ -200,6 +200,10 @@ private void AppendTestRunSummary(ITerminal terminal) AppendLongDuration(terminal, runDuration, wrapInParentheses: false, colorize: false); terminal.AppendLine(); + // Optional "Slowest tests" section (opt-in via --show-slowest-tests). Additive: no-op when the feature is + // off, so the summary stays byte-identical for the default run. + AppendSlowestTests(terminal, assemblies); + // Re-print any handshake failures (orchestrator-only) at the very end so they aren't lost above the summary. // No-op for the in-process host, which never reports handshake failures. AppendHandshakeFailureRecap(terminal); @@ -334,4 +338,75 @@ public void AppendTestDiscoverySummary(ITerminal terminal) AppendLongDuration(terminal, runDuration, wrapInParentheses: false, colorize: false); terminal.AppendLine(); } + + /// + /// Appends the opt-in "Slowest tests" section, ranking the longest-running tests by their reported execution + /// duration. For a single assembly a flat list is rendered; for the multi-assembly orchestrator each assembly + /// gets its own sub-list so the ranking stays scoped per assembly. No-op when the feature is off or when no + /// timed tests were recorded. + /// + private void AppendSlowestTests(ITerminal terminal, List assemblies) + { + int count = _options.SlowestTestsCount; + if (count <= 0) + { + return; + } + + if (_options.ShowAssembly && assemblies.Count > 1) + { + bool headerWritten = false; + foreach (TestProgressState assembly in assemblies) + { + IReadOnlyList<(string DisplayName, TimeSpan Duration)> slowest = assembly.GetSlowestTests(count); + if (slowest.Count == 0) + { + continue; + } + + if (!headerWritten) + { + terminal.AppendLine(); + terminal.AppendLine(TerminalResources.SlowestTests); + headerWritten = true; + } + + terminal.Append(SingleIndentation); + AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly); + terminal.AppendLine(); + foreach ((string displayName, TimeSpan duration) in slowest) + { + terminal.Append(DoubleIndentation); + AppendSlowestTestLine(terminal, displayName, duration); + } + } + + return; + } + + // Single assembly (in-process host, or the orchestrator with a single assembly): a flat list. + IReadOnlyList<(string DisplayName, TimeSpan Duration)> tests = assemblies.Count == 1 + ? assemblies[0].GetSlowestTests(count) + : []; + if (tests.Count == 0) + { + return; + } + + terminal.AppendLine(); + terminal.AppendLine(TerminalResources.SlowestTests); + foreach ((string displayName, TimeSpan duration) in tests) + { + terminal.Append(SingleIndentation); + AppendSlowestTestLine(terminal, displayName, duration); + } + } + + private static void AppendSlowestTestLine(ITerminal terminal, string displayName, TimeSpan duration) + { + AppendLongDuration(terminal, duration, wrapInParentheses: false); + terminal.Append(' '); + terminal.Append(MakeControlCharactersVisible(displayName, true)); + terminal.AppendLine(); + } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.TestCompletion.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.TestCompletion.cs index 7824a5b256..acf7195465 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.TestCompletion.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.TestCompletion.cs @@ -101,6 +101,15 @@ private void TestCompleted( asm.TestNodeResultsState?.RemoveRunningTestNode(testNodeUid); } + // Record the reported duration for the "slowest tests" summary section. All outcomes are included (a slow + // test that then fails is still slow). Called on every completion so a retry that reports no timing clears + // the earlier attempt's stale duration rather than leaving it ranked. Gated on the feature so a run without + // --show-slowest-tests pays no bookkeeping cost. + if (_options.SlowestTestsCount > 0) + { + asm.RecordTestDuration(testNodeUid, displayName, duration); + } + switch (outcome) { case TestOutcome.Error: diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs index 9b326e601b..80523e347a 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs @@ -24,6 +24,7 @@ internal sealed class TerminalTestReporterCommandLineOptionsProvider : CommandLi public const string ShowOutputAllArgument = "all"; public const string ShowOutputFailedArgument = "failed"; public const string ShowOutputNoneArgument = "none"; + public const string ShowSlowestTestsOption = "show-slowest-tests"; public TerminalTestReporterCommandLineOptionsProvider() : base( @@ -40,6 +41,7 @@ public TerminalTestReporterCommandLineOptionsProvider() new(OutputOption, TerminalResources.TerminalOutputOptionDescription, ArgumentArity.ExactlyOne, isHidden: false, isBuiltIn: true), new(ShowStdoutOption, TerminalResources.TerminalShowStdoutOptionDescription, ArgumentArity.ExactlyOne, isHidden: false, isBuiltIn: true), new(ShowStderrOption, TerminalResources.TerminalShowStderrOptionDescription, ArgumentArity.ExactlyOne, isHidden: false, isBuiltIn: true), + new(ShowSlowestTestsOption, TerminalResources.TerminalShowSlowestTestsOptionDescription, ArgumentArity.ExactlyOne, isHidden: false, isBuiltIn: true), ]) { } @@ -61,6 +63,10 @@ public override Task ValidateOptionArgumentsAsync(CommandLineO ShowStdoutOption or ShowStderrOption => arguments.Length == 1 && IsValidShowOutputArgument(arguments[0]) ? ValidationResult.ValidTask : ValidationResult.InvalidTask(TerminalResources.TerminalShowOutputOptionInvalidArgument), + ShowSlowestTestsOption => arguments.Length == 1 + && int.TryParse(arguments[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int count) && count >= 1 + ? ValidationResult.ValidTask + : ValidationResult.InvalidTask(TerminalResources.TerminalShowSlowestTestsOptionInvalidArgument), _ => throw ApplicationStateGuard.Unreachable(), }; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs index a496e9600d..42c7a4a688 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs @@ -76,6 +76,13 @@ internal sealed class TerminalTestReporterOptions /// disables slow-test surfacing. /// public TimeSpan SlowTestThreshold { get; init; } = TimeSpan.FromSeconds(60); + + /// + /// Gets the number of slowest tests to list in the run summary. When greater than zero, a "Slowest tests" + /// section ranking the longest-running tests (by their reported execution duration) is appended to the summary. + /// Zero (the default) disables the section. + /// + public int SlowestTestsCount { get; init; } } [Embedded] diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index ec860abdf7..20a854cc91 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -27,6 +27,13 @@ internal sealed class TestProgressState // This lookup is O(1) because GetAttemptNumberFromInstanceId is called for every reported test result. private readonly Dictionary _instanceIdToAttemptNumber = []; + // Records the last-seen (display name, duration) for every test node, keyed by test node uid, so the + // "slowest tests" summary section can rank them. Keyed by uid (not appended to a list) so a retried test + // replaces its earlier attempt's timing instead of appearing twice, mirroring the pass/fail tally above. + // Only populated when the slowest-tests feature is enabled (the reporter gates the RecordTestDuration call), + // so a run without the feature pays no memory cost here. + private readonly Dictionary _testUidToDuration = []; + public TestProgressState(long id, string assembly, string? targetFramework, string? architecture, IStopwatch stopwatch, bool isDiscovery) { Id = id; @@ -90,6 +97,37 @@ public void ReportSkippedTest(string testNodeUid, string instanceId) public void ReportFailedTest(string testNodeUid, string instanceId) => ReportGenericTestResult(testNodeUid, instanceId, static entry => entry with { Failed = entry.Failed + 1 }, static @this => @this.FailedTests++); + /// + /// Records (or clears) the last-seen duration reported for a test node so it can be ranked in the "slowest + /// tests" summary section. Keyed by so a retry (which re-reports the same uid) + /// replaces the earlier attempt's timing rather than adding a duplicate entry. A + /// means the latest attempt reported no timing, so the earlier attempt's stale + /// duration is removed rather than kept. Only invoked when the slowest-tests feature is enabled. + /// + public void RecordTestDuration(string testNodeUid, string displayName, TimeSpan? duration) + { + if (duration.HasValue) + { + _testUidToDuration[testNodeUid] = (displayName, duration.Value); + } + else + { + _testUidToDuration.Remove(testNodeUid); + } + } + + /// + /// Returns up to recorded tests ordered from slowest to fastest. Ties are broken by + /// display name (ordinal) so the ranking is deterministic for snapshot-based tests. + /// + public IReadOnlyList<(string DisplayName, TimeSpan Duration)> GetSlowestTests(int count) + => count <= 0 || _testUidToDuration.Count == 0 + ? [] + : [.. _testUidToDuration.Values + .OrderByDescending(static entry => entry.Duration) + .ThenBy(static entry => entry.DisplayName, StringComparer.Ordinal) + .Take(count)]; + /// /// Registers a handshake for the given . A previously unseen instance id is a new /// retry attempt and bumps ; re-seeing the current attempt is a no-op. diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.cs.xlf index 81b1f1f7e9..e4ef259113 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.cs.xlf @@ -152,6 +152,11 @@ vynecháno + + Slowest tests: + Slowest tests: + + at v @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout a --show-stderr očekávají jeden parametr s hodnotou All, Failed nebo None. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.de.xlf index fccac03094..d7436b1587 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.de.xlf @@ -152,6 +152,11 @@ übersprungen + + Slowest tests: + Slowest tests: + + at um @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. Die Optionen --show-stdout und --show-stderr erwarten einen einzelnen Parameter mit dem Wert „All“, „Failed“ oder „None“. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.es.xlf index ab16ec03e9..c1cd463f7f 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.es.xlf @@ -152,6 +152,11 @@ omitido + + Slowest tests: + Slowest tests: + + at a las @@ -251,6 +256,16 @@ Esta opción tiene prioridad sobre la marca --no-progress en desuso. --show-stdout y --show-stderr esperan un único parámetro con el valor "All", "Failed" o "None". {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.fr.xlf index 187a083504..42a0f8ae80 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.fr.xlf @@ -152,6 +152,11 @@ ignoré + + Slowest tests: + Slowest tests: + + at sur @@ -251,6 +256,16 @@ Cette option prévaut sur l’indicateur --no-progress déconseillé. --show-stdout et --show-stderr attendent un seul paramètre avec la valeur « All », « Failed » ou « None ». {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.it.xlf index a868e16818..25591f81cc 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.it.xlf @@ -152,6 +152,11 @@ ignorato + + Slowest tests: + Slowest tests: + + at a @@ -251,6 +256,16 @@ Questa opzione ha la precedenza sul flag --no-progress deprecato. --show-stdout e --show-stderr prevedono un singolo parametro con valore 'All', 'Failed' o 'None'. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ja.xlf index 38cd8fb631..aae0e87421 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ja.xlf @@ -152,6 +152,11 @@ スキップされました + + Slowest tests: + Slowest tests: + + at 場所: @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout と --show-stderr には、値が 'All'、'Failed'、または 'None' の 1 つのパラメーターが必要です。 {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ko.xlf index 57cbf5aa16..0990f0c920 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ko.xlf @@ -152,6 +152,11 @@ 건너뜀 + + Slowest tests: + Slowest tests: + + at 위치 @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout 및 --show-stderr에는 값이 'All', 'Failed' 또는 'None'인 단일 매개 변수가 필요합니다. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pl.xlf index a9dbaa08af..7b504025e4 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pl.xlf @@ -152,6 +152,11 @@ pominięte + + Slowest tests: + Slowest tests: + + at o @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. Polecenia --show-stdout i --show-stderr oczekują pojedynczego parametru o wartości „All”, „Failed” lub „None”. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pt-BR.xlf index 97633e3189..6cd864785d 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.pt-BR.xlf @@ -152,6 +152,11 @@ ignorado + + Slowest tests: + Slowest tests: + + at em @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout e --show-stderr esperam um único parâmetro com o valor 'All', 'Failed' ou 'None'. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ru.xlf index 4816e69a6a..4d861f34b2 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.ru.xlf @@ -152,6 +152,11 @@ пропущено + + Slowest tests: + Slowest tests: + + at в @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout и --show-stderr принимают один параметр со значением "All" (Все), "Failed" (Сбой), "None" (Нет). {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.tr.xlf index a9062186f1..fc25a1d067 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.tr.xlf @@ -152,6 +152,11 @@ atlandı + + Slowest tests: + Slowest tests: + + at şu yöntemle: @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout ve --show-stderr, değeri 'All', 'Failed' veya 'None' olan tek bir parametre bekliyor. {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hans.xlf index 3aa50ae450..eb14a59b43 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hans.xlf @@ -152,6 +152,11 @@ 已跳过 + + Slowest tests: + Slowest tests: + + at 在 @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout and --show-stderr 需要值为“All”、“Failed”或“None”的单个参数。 {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hant.xlf index 21b433726e..70faf69c50 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/xlf/TerminalResources.zh-Hant.xlf @@ -152,6 +152,11 @@ 已跳過 + + Slowest tests: + Slowest tests: + + at 於 @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag. --show-stdout 和 --show-stderr 需接收一個參數,其值必須為「All」、「Failed」或「None」。 {Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"} + + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. + + + + --show-slowest-tests expects a single positive integer parameter. + --show-slowest-tests expects a single positive integer parameter. + {Locked="--show-slowest-tests"} + Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.Initialization.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.Initialization.cs index 79b3028b68..25942796c7 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.Initialization.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.Initialization.cs @@ -142,6 +142,7 @@ await _policiesService.RegisterOnAbortCallbackAsync( OutputShowMode showStdout = GetShowOutputMode(_commandLineOptions, TerminalTestReporterCommandLineOptionsProvider.ShowStdoutOption, isLLMEnvironment); OutputShowMode showStderr = GetShowOutputMode(_commandLineOptions, TerminalTestReporterCommandLineOptionsProvider.ShowStderrOption, isLLMEnvironment); + int slowestTestsCount = GetSlowestTestsCount(_commandLineOptions); Func shouldShowProgress = noProgress // User preference is to not show progress. @@ -170,9 +171,22 @@ await _policiesService.RegisterOnAbortCallbackAsync( ShowStderr = showStderr, HeartbeatSilenceThreshold = GetProgressThreshold(_environment, MTP_PROGRESS_SILENCE_SECONDS, defaultSeconds: 30), SlowTestThreshold = GetProgressThreshold(_environment, MTP_PROGRESS_SLOW_TEST_SECONDS, defaultSeconds: 60), + SlowestTestsCount = slowestTestsCount, }); } + // Reads the --show-slowest-tests option, returning the requested count of slowest tests to list in the + // summary. Returns 0 (feature off) when the option is absent. The value has already been validated to be a + // positive integer by TerminalTestReporterCommandLineOptionsProvider. Internal for unit testing the parse seam + // that feeds TerminalTestReporterOptions.SlowestTestsCount. + internal static int GetSlowestTestsCount(ICommandLineOptions commandLineOptions) + => commandLineOptions.TryGetOptionArgumentList(TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption, out string[]? arguments) + && arguments is [string value] + && int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int count) + && count >= 1 + ? count + : 0; + // Reads an integer number of seconds from the given environment variable, falling back to // when unset or invalid. A value of 0 disables the related // heartbeat rule (returns TimeSpan.Zero). Negative or non-integer values are ignored. diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs index a27eecf957..80f264a9fc 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -82,6 +82,8 @@ This option takes precedence over the deprecated --no-progress flag. The directory where the test results are going to be placed. If the specified directory doesn't exist, it's created. The default is TestResults in the directory that contains the test application. + --show-slowest-tests + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. --show-stderr Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs index b18fdd0a8b..1b31bbfbe7 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs @@ -76,6 +76,8 @@ This option takes precedence over the deprecated --no-progress flag. The directory where the test results are going to be placed. If the specified directory doesn't exist, it's created. The default is TestResults in the directory that contains the test application. + --show-slowest-tests + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. --show-stderr Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). @@ -409,6 +411,10 @@ Note that this is slowing down the test execution. Valid values are 'auto' (default), 'on' (also accepts 'true', 'enable', '1') or 'off' (also accepts 'false', 'disable', '0'). 'auto' shows progress unless the terminal cannot update in place (for example with --no-ansi or in CI). This option takes precedence over the deprecated --no-progress flag. + --show-slowest-tests + Arity: 1 + Hidden: False + Description: Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. --show-stderr Arity: 1 Hidden: False diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index 1be11905c5..dc8fd587b1 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -76,6 +76,8 @@ This option takes precedence over the deprecated --no-progress flag. The directory where the test results are going to be placed. If the specified directory doesn't exist, it's created. The default is TestResults in the directory that contains the test application. + --show-slowest-tests + Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer. --show-stderr Determines when to show captured error output of a test. Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an LLM/AI agent environment is detected). @@ -303,6 +305,10 @@ Note that this is slowing down the test execution\. Valid values are 'auto' \(default\), 'on' \(also accepts 'true', 'enable', '1'\) or 'off' \(also accepts 'false', 'disable', '0'\). 'auto' shows progress unless the terminal cannot update in place \(for example with --no-ansi or in CI\). This option takes precedence over the deprecated --no-progress flag. + --show-slowest-tests + Arity: 1 + Hidden: False + Description: Show the specified number of slowest tests \(by reported execution duration\) in the run summary. Expects a positive integer. --show-stderr Arity: 1 Hidden: False diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProviderTests.cs index 72e48cbe50..8ec8871219 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProviderTests.cs @@ -3,11 +3,13 @@ using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Extensions.CommandLine; +using Microsoft.Testing.Platform.OutputDevice; using Microsoft.Testing.Platform.OutputDevice.Terminal; namespace Microsoft.Testing.Platform.UnitTests; [TestClass] +[UnsupportedOSPlatform("browser")] public sealed class TerminalTestReporterCommandLineOptionsProviderTests { private readonly TerminalTestReporterCommandLineOptionsProvider _provider = new(); @@ -128,6 +130,81 @@ public void GetCommandLineOptions_StillIncludesNoProgressOption() Assert.IsTrue(option.IsBuiltIn); } + [TestMethod] + [DataRow("1")] + [DataRow("5")] + [DataRow("100")] + public async Task ValidateOptionArguments_ShowSlowestTestsOption_AcceptsPositiveIntegers(string value) + { + CommandLineOption option = GetOption(TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption); + + ValidationResult result = await _provider.ValidateOptionArgumentsAsync(option, [value]); + + Assert.IsTrue(result.IsValid, $"Expected '{value}' to be a valid --show-slowest-tests value, but got: {result.ErrorMessage}"); + } + + [TestMethod] + [DataRow("0")] + [DataRow("-1")] + [DataRow("abc")] + [DataRow("1.5")] + [DataRow("")] + public async Task ValidateOptionArguments_ShowSlowestTestsOption_RejectsInvalidValues(string value) + { + CommandLineOption option = GetOption(TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption); + + ValidationResult result = await _provider.ValidateOptionArgumentsAsync(option, [value]); + + Assert.IsFalse(result.IsValid, $"Expected '{value}' to be rejected as a --show-slowest-tests value but it was accepted."); + Assert.IsNotNull(result.ErrorMessage); + } + + [TestMethod] + public async Task ValidateOptionArguments_ShowSlowestTestsOption_RejectsMultipleArguments() + { + CommandLineOption option = GetOption(TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption); + + ValidationResult result = await _provider.ValidateOptionArgumentsAsync(option, ["1", "2"]); + + Assert.IsFalse(result.IsValid, "Expected --show-slowest-tests to reject more than one argument."); + Assert.IsNotNull(result.ErrorMessage); + } + + [TestMethod] + public void GetCommandLineOptions_IncludesShowSlowestTestsOption() + { + CommandLineOption option = GetOption(TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption); + + Assert.AreEqual(ArgumentArity.ExactlyOne, option.Arity); + Assert.IsFalse(option.IsHidden); + Assert.IsTrue(option.IsBuiltIn); + } + + // Wiring test: the parsed --show-slowest-tests value must reach the reporter via + // TerminalOutputDevice.GetSlowestTestsCount (which feeds TerminalTestReporterOptions.SlowestTestsCount), so a + // validation/parse regression can't leave a help-only option. + [TestMethod] + [DataRow("1", 1)] + [DataRow("5", 5)] + [DataRow("100", 100)] + public void GetSlowestTestsCount_WhenOptionSetToPositiveInteger_ReturnsThatCount(string argument, int expected) + { + var options = new Helpers.TestCommandLineOptions(new Dictionary + { + [TerminalTestReporterCommandLineOptionsProvider.ShowSlowestTestsOption] = [argument], + }); + + Assert.AreEqual(expected, TerminalOutputDevice.GetSlowestTestsCount(options)); + } + + [TestMethod] + public void GetSlowestTestsCount_WhenOptionAbsent_ReturnsZero() + { + var options = new Helpers.TestCommandLineOptions([]); + + Assert.AreEqual(0, TerminalOutputDevice.GetSlowestTestsCount(options)); + } + private CommandLineOption GetOption(string name) => _provider.GetCommandLineOptions().Single(o => o.Name == name); } 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 91169fa4e2..213f47812d 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -1834,6 +1834,203 @@ public void AssemblyRunStarted_AfterRetry_RendersLatestAttemptCounts() Assert.Contains(ExpectedCounts(1, 0, 0), assemblyLine); } + [TestMethod] + public void TestExecutionCompleted_WhenShowSlowestTestsSet_PrintsFlatSlowestSectionRankedByDuration() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, static () => false, new TerminalTestReporterOptions + { + AnsiMode = AnsiMode.NoAnsi, + ShowProgress = () => false, + SlowestTestsCount = 2, + }); + + terminalReporter.TestExecutionStarted(DateTimeOffset.MinValue, 1, isDiscovery: false, isHelp: false, isRetry: false); + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", "0", "0"); + + // A failed slowest test and a passed medium test should surface (all outcomes are eligible); the fast skipped + // test falls outside the requested top-2. + terminalReporter.TestCompleted("0", testNodeUid: "SlowFailedTest", "SlowFailedTest", TestOutcome.Fail, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: "boom", exception: null, expected: null, actual: null, standardOutput: null, errorOutput: null); + terminalReporter.TestCompleted("0", testNodeUid: "MediumPassedTest", "MediumPassedTest", TestOutcome.Passed, TimeSpan.FromSeconds(5), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput: null, errorOutput: null); + terminalReporter.TestCompleted("0", testNodeUid: "FastSkippedTest", "FastSkippedTest", TestOutcome.Skipped, TimeSpan.FromSeconds(1), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput: null, errorOutput: null); + + terminalReporter.AssemblyRunCompleted("0"); + terminalReporter.TestExecutionCompleted(DateTimeOffset.MaxValue, exitCode: null); + + string output = stringBuilderConsole.Output; + int headerIndex = output.IndexOf(TerminalResources.SlowestTests, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, headerIndex, $"Expected a slowest-tests section. Output:{Environment.NewLine}{output}"); + + string slowestSection = output.Substring(headerIndex); + int slowIndex = slowestSection.IndexOf("SlowFailedTest", StringComparison.Ordinal); + int mediumIndex = slowestSection.IndexOf("MediumPassedTest", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, slowIndex, "Slowest test should be listed."); + Assert.IsGreaterThanOrEqualTo(0, mediumIndex, "Second-slowest test should be listed."); + Assert.IsLessThan(mediumIndex, slowIndex, "Tests should be listed from slowest to fastest."); + Assert.IsFalse(slowestSection.Contains("FastSkippedTest", StringComparison.Ordinal), "The fastest test should not appear in the top-2 slowest section."); + } + + [TestMethod] + public void TestExecutionCompleted_WhenShowSlowestTestsNotSet_DoesNotPrintSlowestSection() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, static () => false, new TerminalTestReporterOptions + { + AnsiMode = AnsiMode.NoAnsi, + ShowProgress = () => false, + }); + + terminalReporter.TestExecutionStarted(DateTimeOffset.MinValue, 1, isDiscovery: false, isHelp: false, isRetry: false); + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", "0", "0"); + terminalReporter.TestCompleted("0", testNodeUid: "SomeTest", "SomeTest", TestOutcome.Passed, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput: null, errorOutput: null); + terminalReporter.AssemblyRunCompleted("0"); + terminalReporter.TestExecutionCompleted(DateTimeOffset.MaxValue, exitCode: null); + + Assert.IsFalse(stringBuilderConsole.Output.Contains(TerminalResources.SlowestTests, StringComparison.Ordinal)); + } + + // Verifies the reporter's multi-assembly rendering path: when SlowestTestsCount is set and more than one + // assembly is registered (as the dotnet test orchestrator does), each assembly gets its own slowest-tests + // sub-list. This exercises the shared reporter directly; note that wiring `dotnet test --show-slowest-tests` + // to set SlowestTestsCount is owned by the dotnet/sdk CLI (TerminalReporterContract.props excludes the MTP + // options provider) and is out of scope for this repo. + [TestMethod] + public void TestExecutionCompleted_WithMultipleAssemblies_WhenShowSlowestTestsSet_PrintsPerAssemblySlowest() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + { + AnsiMode = AnsiMode.NoAnsi, + ShowProgress = () => false, + ShowAssembly = true, + ShowAssemblyStartAndComplete = false, + SlowestTestsCount = 1, + }); + + terminalReporter.TestExecutionStarted(DateTimeOffset.MinValue, workerCount: 2, isDiscovery: false, isHelp: false, isRetry: false); + + string assemblyA = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\repo\A.Tests.dll" : "/repo/A.Tests.dll"; + string assemblyB = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\repo\B.Tests.dll" : "/repo/B.Tests.dll"; + terminalReporter.AssemblyRunStarted(assemblyA, "net9.0", "x64", executionId: "exec-A", instanceId: "inst-A"); + terminalReporter.AssemblyRunStarted(assemblyB, "net9.0", "x64", executionId: "exec-B", instanceId: "inst-B"); + + ReportOrchestratorTestWithDuration(terminalReporter, assemblyA, "exec-A", "inst-A", "a-slow", TestOutcome.Passed, TimeSpan.FromSeconds(9)); + ReportOrchestratorTestWithDuration(terminalReporter, assemblyA, "exec-A", "inst-A", "a-fast", TestOutcome.Passed, TimeSpan.FromSeconds(7)); + ReportOrchestratorTestWithDuration(terminalReporter, assemblyB, "exec-B", "inst-B", "b-slow", TestOutcome.Passed, TimeSpan.FromSeconds(6)); + ReportOrchestratorTestWithDuration(terminalReporter, assemblyB, "exec-B", "inst-B", "b-fast", TestOutcome.Passed, TimeSpan.FromSeconds(2)); + + terminalReporter.AssemblyRunCompleted(executionId: "exec-A", exitCode: 0, outputData: null, errorData: null); + terminalReporter.AssemblyRunCompleted(executionId: "exec-B", exitCode: 0, outputData: null, errorData: null); + terminalReporter.TestExecutionCompleted(DateTimeOffset.MaxValue, exitCode: 0); + + string output = stringBuilderConsole.Output; + int headerIndex = output.IndexOf(TerminalResources.SlowestTests, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, headerIndex, $"Expected a slowest-tests section. Output:{Environment.NewLine}{output}"); + + string slowestSection = output.Substring(headerIndex); + // Durations are chosen so a-fast (7s) is globally slower than b-slow (6s): a merged global ranking would + // surface both A tests and drop b-slow, so asserting b-slow is present and a-fast is absent proves the + // ranking is scoped per assembly (each assembly contributes only its own top-1). + Assert.Contains("a-slow", slowestSection); + Assert.Contains("b-slow", slowestSection); + Assert.IsFalse(slowestSection.Contains("a-fast", StringComparison.Ordinal), "Faster test of assembly A should not appear in its top-1 slowest."); + Assert.IsFalse(slowestSection.Contains("b-fast", StringComparison.Ordinal), "Faster test of assembly B should not appear in its top-1 slowest."); + } + + // Regression test for the retry case: a timed first attempt followed by a retry that reports no timing must + // drop the stale first-attempt duration instead of keeping it ranked in the slowest section. + [TestMethod] + public void TestExecutionCompleted_WhenTimedTestRetriedWithoutTiming_DropsStaleDurationFromSlowest() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + { + AnsiMode = AnsiMode.NoAnsi, + ShowProgress = () => false, + ShowAssembly = true, + ShowAssemblyStartAndComplete = false, + SlowestTestsCount = 5, + }); + + terminalReporter.TestExecutionStarted(DateTimeOffset.MinValue, workerCount: 1, isDiscovery: false, isHelp: false, isRetry: true); + + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\repo\Flaky.Tests.dll" : "/repo/Flaky.Tests.dll"; + const string executionId = "exec-flaky"; + + // Attempt 1: the flaky test fails with a large (10s) reported duration, and a stable test passes quickly. + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", executionId, instanceId: "inst-1"); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-1", "flaky", TestOutcome.Fail, TimeSpan.FromSeconds(10)); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-1", "stable", TestOutcome.Passed, TimeSpan.FromSeconds(1)); + + // Attempt 2 (new instance id): the retry passes but reports no timing. + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", executionId, instanceId: "inst-2"); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-2", "flaky", TestOutcome.Passed, duration: null); + + terminalReporter.AssemblyRunCompleted(executionId, exitCode: 0, outputData: null, errorData: null); + terminalReporter.TestExecutionCompleted(DateTimeOffset.MaxValue, exitCode: 0); + + string output = stringBuilderConsole.Output; + int headerIndex = output.IndexOf(TerminalResources.SlowestTests, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, headerIndex, $"Expected a slowest-tests section. Output:{Environment.NewLine}{output}"); + + string slowestSection = output.Substring(headerIndex); + Assert.Contains("stable", slowestSection); + Assert.IsFalse(slowestSection.Contains("flaky", StringComparison.Ordinal), "The retried test's stale first-attempt duration should have been dropped once the retry reported no timing."); + } + + // Regression test for the retry-replacement behavior: when the same uid is reported across two attempts with + // different durations, only the latest attempt's duration must be ranked (not the earlier attempt's). + [TestMethod] + public void TestExecutionCompleted_WhenTestRetriedWithDifferentDuration_RanksOnlyLatestAttempt() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + { + AnsiMode = AnsiMode.NoAnsi, + ShowProgress = () => false, + ShowAssembly = true, + ShowAssemblyStartAndComplete = false, + SlowestTestsCount = 5, + }); + + terminalReporter.TestExecutionStarted(DateTimeOffset.MinValue, workerCount: 1, isDiscovery: false, isHelp: false, isRetry: true); + + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\repo\Flaky.Tests.dll" : "/repo/Flaky.Tests.dll"; + const string executionId = "exec-flaky"; + + // Attempt 1: the flaky test fails taking 10s; another test passes taking 5s. + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", executionId, instanceId: "inst-1"); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-1", "flaky", TestOutcome.Fail, TimeSpan.FromSeconds(10)); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-1", "other", TestOutcome.Passed, TimeSpan.FromSeconds(5)); + + // Attempt 2 (new instance id): the retry passes quickly (2s). + terminalReporter.AssemblyRunStarted(assembly, "net9.0", "x64", executionId, instanceId: "inst-2"); + ReportOrchestratorTestWithDuration(terminalReporter, assembly, executionId, "inst-2", "flaky", TestOutcome.Passed, TimeSpan.FromSeconds(2)); + + terminalReporter.AssemblyRunCompleted(executionId, exitCode: 0, outputData: null, errorData: null); + terminalReporter.TestExecutionCompleted(DateTimeOffset.MaxValue, exitCode: 0); + + string output = stringBuilderConsole.Output; + int headerIndex = output.IndexOf(TerminalResources.SlowestTests, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, headerIndex, $"Expected a slowest-tests section. Output:{Environment.NewLine}{output}"); + + string slowestSection = output.Substring(headerIndex); + // The stale 10s first attempt must not be ranked; the latest attempt's 2s wins, so 'other' (5s) ranks above + // 'flaky' (2s). If the first attempt leaked, 'flaky' would rank first and the 10s duration would appear. + Assert.IsFalse(slowestSection.Contains("10s", StringComparison.Ordinal), "The first attempt's 10s duration must not be ranked after the retry replaced it."); + int otherIndex = slowestSection.IndexOf("other", StringComparison.Ordinal); + int flakyIndex = slowestSection.IndexOf("flaky", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, otherIndex, "Expected 'other' to be listed."); + Assert.IsGreaterThanOrEqualTo(0, flakyIndex, "Expected 'flaky' to be listed."); + Assert.IsLessThan(flakyIndex, otherIndex, "'other' (5s) should rank above the retried 'flaky' (2s), proving only the latest attempt's duration is used."); + } + private static TerminalTestReporter CreateOrchestratorReporter(StringBuilderConsole console, bool showAssemblyStartAndComplete = true) => new(console, new TerminalTestReporterOptions { @@ -1861,6 +2058,24 @@ private static void ReportOrchestratorTest(TerminalTestReporter reporter, string standardOutput: null, errorOutput: null); + private static void ReportOrchestratorTestWithDuration(TerminalTestReporter reporter, string assembly, string executionId, string instanceId, string testUid, TestOutcome outcome, TimeSpan? duration) + => reporter.TestCompleted( + assembly, + targetFramework: "net9.0", + architecture: "x64", + executionId, + instanceId, + testNodeUid: testUid, + displayName: testUid, + informativeMessage: null, + outcome, + duration, + exceptions: null, + expected: null, + actual: null, + standardOutput: null, + errorOutput: null); + private static string GetAssemblySummaryLine(string output, string assemblyPath) => Array.Find( output.Split('\n'),