Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@
<data name="SkippedLowercase" xml:space="preserve">
<value>skipped</value>
</data>
<data name="SlowestTests" xml:space="preserve">
<value>Slowest tests:</value>
</data>
<data name="TotalLowercase" xml:space="preserve">
<value>total</value>
</data>
Expand Down Expand Up @@ -259,6 +262,13 @@ Valid values are 'All', 'Failed', 'None'. Default is 'All' (or 'Failed' when an
<value>--show-stdout and --show-stderr expect a single parameter with value 'All', 'Failed', or 'None'.</value>
<comment>{Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"}</comment>
</data>
<data name="TerminalShowSlowestTestsOptionDescription" xml:space="preserve">
<value>Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</value>
Comment thread
Evangelink marked this conversation as resolved.
Resolved
</data>
Comment thread
Evangelink marked this conversation as resolved.
Resolved
<data name="TerminalShowSlowestTestsOptionInvalidArgument" xml:space="preserve">
<value>--show-slowest-tests expects a single positive integer parameter.</value>
<comment>{Locked="--show-slowest-tests"}</comment>
</data>
<data name="StandardError" xml:space="preserve">
<value>Error output</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -334,4 +338,75 @@ public void AppendTestDiscoverySummary(ITerminal terminal)
AppendLongDuration(terminal, runDuration, wrapInParentheses: false, colorize: false);
terminal.AppendLine();
}

/// <summary>
/// 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.
/// </summary>
private void AppendSlowestTests(ITerminal terminal, List<TestProgressState> 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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),
])
{
}
Expand All @@ -61,6 +63,10 @@ public override Task<ValidationResult> 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),
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Comment thread
Evangelink marked this conversation as resolved.
Resolved
_ => throw ApplicationStateGuard.Unreachable(),
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ internal sealed class TerminalTestReporterOptions
/// disables slow-test surfacing.
/// </summary>
public TimeSpan SlowTestThreshold { get; init; } = TimeSpan.FromSeconds(60);

/// <summary>
/// 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.
/// </summary>
public int SlowestTestsCount { get; init; }
}

[Embedded]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, int> _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<string, (string DisplayName, TimeSpan Duration)> _testUidToDuration = [];

public TestProgressState(long id, string assembly, string? targetFramework, string? architecture, IStopwatch stopwatch, bool isDiscovery)
{
Id = id;
Expand Down Expand Up @@ -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++);

/// <summary>
/// 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 <paramref name="testNodeUid"/> so a retry (which re-reports the same uid)
/// replaces the earlier attempt's timing rather than adding a duplicate entry. A <see langword="null"/>
/// <paramref name="duration"/> 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.
/// </summary>
public void RecordTestDuration(string testNodeUid, string displayName, TimeSpan? duration)
{
if (duration.HasValue)
{
_testUidToDuration[testNodeUid] = (displayName, duration.Value);
}
else
{
_testUidToDuration.Remove(testNodeUid);
}
}

/// <summary>
/// Returns up to <paramref name="count"/> recorded tests ordered from slowest to fastest. Ties are broken by
/// display name (ordinal) so the ranking is deterministic for snapshot-based tests.
/// </summary>
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)];

/// <summary>
/// Registers a handshake for the given <paramref name="instanceId"/>. A previously unseen instance id is a new
/// retry attempt and bumps <see cref="TryCount"/>; re-seeing the current attempt is a no-op.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@
<target state="translated">vynecháno</target>
<note />
</trans-unit>
<trans-unit id="SlowestTests">
<source>Slowest tests:</source>
<target state="new">Slowest tests:</target>
<note />
</trans-unit>
<trans-unit id="StackFrameAt">
<source>at</source>
<target state="translated">v</target>
Expand Down Expand Up @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag.</target>
<target state="translated">--show-stdout a --show-stderr očekávají jeden parametr s hodnotou All, Failed nebo None.</target>
<note>{Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"}</note>
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionDescription">
<source>Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</source>
<target state="new">Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</target>
<note />
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionInvalidArgument">
<source>--show-slowest-tests expects a single positive integer parameter.</source>
<target state="new">--show-slowest-tests expects a single positive integer parameter.</target>
<note>{Locked="--show-slowest-tests"}</note>
</trans-unit>
<trans-unit id="TerminalShowStderrOptionDescription">
<source>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).</source>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@
<target state="translated">übersprungen</target>
<note />
</trans-unit>
<trans-unit id="SlowestTests">
<source>Slowest tests:</source>
<target state="new">Slowest tests:</target>
<note />
</trans-unit>
<trans-unit id="StackFrameAt">
<source>at</source>
<target state="translated">um</target>
Expand Down Expand Up @@ -251,6 +256,16 @@ This option takes precedence over the deprecated --no-progress flag.</target>
<target state="translated">Die Optionen --show-stdout und --show-stderr erwarten einen einzelnen Parameter mit dem Wert „All“, „Failed“ oder „None“.</target>
<note>{Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"}</note>
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionDescription">
<source>Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</source>
<target state="new">Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</target>
<note />
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionInvalidArgument">
<source>--show-slowest-tests expects a single positive integer parameter.</source>
<target state="new">--show-slowest-tests expects a single positive integer parameter.</target>
<note>{Locked="--show-slowest-tests"}</note>
</trans-unit>
<trans-unit id="TerminalShowStderrOptionDescription">
<source>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).</source>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@
<target state="translated">omitido</target>
<note />
</trans-unit>
<trans-unit id="SlowestTests">
<source>Slowest tests:</source>
<target state="new">Slowest tests:</target>
<note />
</trans-unit>
<trans-unit id="StackFrameAt">
<source>at</source>
<target state="translated">a las</target>
Expand Down Expand Up @@ -251,6 +256,16 @@ Esta opción tiene prioridad sobre la marca --no-progress en desuso.</target>
<target state="translated">--show-stdout y --show-stderr esperan un único parámetro con el valor "All", "Failed" o "None".</target>
<note>{Locked="--show-stdout"}{Locked="--show-stderr"}{Locked="All"}{Locked="Failed"}{Locked="None"}</note>
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionDescription">
<source>Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</source>
<target state="new">Show the specified number of slowest tests (by reported execution duration) in the run summary. Expects a positive integer.</target>
<note />
</trans-unit>
<trans-unit id="TerminalShowSlowestTestsOptionInvalidArgument">
<source>--show-slowest-tests expects a single positive integer parameter.</source>
<target state="new">--show-slowest-tests expects a single positive integer parameter.</target>
<note>{Locked="--show-slowest-tests"}</note>
</trans-unit>
<trans-unit id="TerminalShowStderrOptionDescription">
<source>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).</source>
Expand Down
Loading
Loading