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 @@ -83,7 +83,7 @@ private string BuildJson(CapturedTestResult[] results, DateTimeOffset finishTime
int skipped = 0;
int timedout = 0;
int errored = 0;
TimeSpan totalDuration = TimeSpan.Zero;
TimeSpan elapsedTime = finishTime - _testStartTime;

// First pass: count how many entries each UID is going to produce so we can
// annotate rows that share a UID with "attemptIndex"/"attemptOf". This lets the
Expand Down Expand Up @@ -147,8 +147,6 @@ private string BuildJson(CapturedTestResult[] results, DateTimeOffset finishTime
first = false;

CountOutcome(r.Outcome, ref passed, ref failed, ref skipped, ref timedout, ref errored);
totalDuration += r.Duration;

int attemptOf = countByUid[r.Uid];
int attemptIndex = emittedByUid.TryGetValue(r.Uid, out int alreadyEmitted) ? alreadyEmitted + 1 : 1;
emittedByUid[r.Uid] = attemptIndex;
Expand Down Expand Up @@ -276,7 +274,7 @@ private string BuildJson(CapturedTestResult[] results, DateTimeOffset finishTime
sb.Append(',');
AppendNumberPair(sb, "errored", errored.ToString(CultureInfo.InvariantCulture));
sb.Append(',');
AppendNumberPair(sb, "totalDurationMs", totalDuration.TotalMilliseconds.ToString("F3", CultureInfo.InvariantCulture));
AppendNumberPair(sb, "totalDurationMs", elapsedTime.TotalMilliseconds.ToString("F3", CultureInfo.InvariantCulture));
sb.Append('}');

sb.Append('}');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,11 @@ .. tests
.ThenBy(test => test.OriginalTestIndex),
];

(JsonArray mergedTests, int passed, int failed, int skipped, int timedOut, int errored, double totalDurationMs, int? flaky) =
(JsonArray mergedTests, int passed, int failed, int skipped, int timedOut, int errored, int? flaky) =
mode == HtmlMergeMode.CollapseRetryAttempts
? CollapseRetryAttempts(orderedTests)
: ConcatenateTests(orderedTests);
double totalDurationMs = (latestEndTime!.Value - earliestStartTime!.Value).TotalMilliseconds;
Comment thread
Evangelink marked this conversation as resolved.
Resolved

bool hasCommonFramework = TryGetCommonFramework(reports, out string framework, out string frameworkUid, out string frameworkVersion);
var summary = new JsonObject
Expand Down Expand Up @@ -187,7 +188,7 @@ .. tests
/// than one row shares the same test identity (e.g. the same test UID appearing in more than one shard), so
/// nothing is silently collapsed away.
/// </summary>
private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedOut, int Errored, double TotalDurationMs, int? Flaky) ConcatenateTests(
private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedOut, int Errored, int? Flaky) ConcatenateTests(
MergedTest[] orderedTests)
{
var countByIdentity = new Dictionary<string, int>(StringComparer.Ordinal);
Expand All @@ -203,15 +204,13 @@ private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedO
int skipped = 0;
int timedOut = 0;
int errored = 0;
double totalDurationMs = 0;

for (int i = 0; i < orderedTests.Length; i++)
{
MergedTest mergedTest = orderedTests[i];
JsonObject test = mergedTest.Test;
string identity = CreateTestIdentity(mergedTest);
string outcome = ReadRequiredString(test, "outcome");
double durationMs = ReadRequiredDouble(test, "durationMs");
_ = ReadRequiredDouble(test, "durationMs");

test["rowKey"] = i;
_ = test.Remove("attemptIndex");
Expand All @@ -232,11 +231,10 @@ private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedO
}

CountOutcome(outcome, ref passed, ref failed, ref skipped, ref timedOut, ref errored);
totalDurationMs += durationMs;
mergedTests.Add((JsonNode)test);
}

return (mergedTests, passed, failed, skipped, timedOut, errored, totalDurationMs, null);
return (mergedTests, passed, failed, skipped, timedOut, errored, null);
}

/// <summary>
Expand All @@ -246,9 +244,9 @@ private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedO
/// duration, and whichever error/output detail fields they carried. A test whose final outcome is "passed"
/// after at least one non-passed prior attempt is additionally flagged "flaky" so it stays visibly
/// distinguishable from a test that has always passed. Logical result counts use only the final occurrence,
/// while total duration includes every physical attempt so retry cost remains visible.
/// while the merged report duration spans from the earliest input start time to the latest input end time.
/// </summary>
private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedOut, int Errored, double TotalDurationMs, int? Flaky) CollapseRetryAttempts(
private static (JsonArray Tests, int Passed, int Failed, int Skipped, int TimedOut, int Errored, int? Flaky) CollapseRetryAttempts(
MergedTest[] orderedTests)
{
HashSet<(int ReportIndex, string BaseIdentity)> ambiguousIdentities =
Expand Down Expand Up @@ -290,14 +288,12 @@ .. orderedTests
int timedOut = 0;
int errored = 0;
int flaky = 0;
double totalDurationMs = 0;

for (int i = 0; i < slots.Count; i++)
{
(MergedTest final, List<JsonObject> priors) = slots[i];
JsonObject test = final.Test;
string outcome = ReadRequiredString(test, "outcome");
double durationMs = ReadRequiredDouble(test, "durationMs");
_ = ReadRequiredDouble(test, "durationMs");

test["rowKey"] = i;
_ = test.Remove("attemptIndex");
Expand Down Expand Up @@ -334,16 +330,10 @@ .. orderedTests
}

CountOutcome(outcome, ref passed, ref failed, ref skipped, ref timedOut, ref errored);
totalDurationMs += durationMs;
foreach (JsonObject prior in priors)
{
totalDurationMs += ReadRequiredDouble(prior, "durationMs");
}

mergedTests.Add((JsonNode)test);
}

return (mergedTests, passed, failed, skipped, timedOut, errored, totalDurationMs, flaky);
return (mergedTests, passed, failed, skipped, timedOut, errored, flaky);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests;

[TestClass]
[DoNotParallelize]
public class HtmlReportTests : AcceptanceTestBase<HtmlReportTests.TestAssetFixture>
{
[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
Expand Down Expand Up @@ -79,6 +80,53 @@ public async Task Html_WhenTestHostCrashes_RecoversCompletedResultsAndMarksRepor
Assert.Contains("Tests absent from this report did not necessarily pass.", content);
}

[TestMethod]
public async Task Html_WhenTestsRunInParallel_DurationSummaryUsesWallClockTime()
{
string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"));
string reportPath = Path.Combine(resultDirectory, "parallel.html");
var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, TargetFrameworks.NetCurrent);

TestHostResult testHostResult = await testHost.ExecuteAsync(
$"--report-html --report-html-filename parallel.html --results-directory \"{resultDirectory}\"",
new() { ["PARALLELTESTS"] = "1" },
cancellationToken: TestContext.CancellationToken);

testHostResult.AssertExitCodeIs(ExitCode.Success);
Assert.IsTrue(File.Exists(reportPath), $"Expected HTML report was not found at '{reportPath}'.");

string htmlReport = File.ReadAllText(reportPath);
const string htmlDataStart = "<script id=\"mtp-data\" type=\"application/json\">";
const string htmlDataEnd = "</script>";
int htmlDataStartIndex = htmlReport.IndexOf(htmlDataStart, StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, htmlDataStartIndex, htmlReport);
htmlDataStartIndex += htmlDataStart.Length;
int htmlDataEndIndex = htmlReport.IndexOf(htmlDataEnd, htmlDataStartIndex, StringComparison.Ordinal);
Assert.IsGreaterThan(htmlDataStartIndex, htmlDataEndIndex, htmlReport);

using var htmlDocument = System.Text.Json.JsonDocument.Parse(
htmlReport.Substring(htmlDataStartIndex, htmlDataEndIndex - htmlDataStartIndex));
System.Text.Json.JsonElement root = htmlDocument.RootElement;
System.Text.Json.JsonElement[] tests =
[
.. root.GetProperty("tests").EnumerateArray()
];
DateTimeOffset[] testStartTimes = [.. tests.Select(test => test.GetProperty("startTime").GetDateTimeOffset())];
DateTimeOffset[] testEndTimes = [.. tests.Select(test => test.GetProperty("endTime").GetDateTimeOffset())];
double[] testDurations = [.. tests.Select(test => test.GetProperty("durationMs").GetDouble())];
DateTimeOffset reportStartTime = root.GetProperty("startTime").GetDateTimeOffset();
DateTimeOffset reportEndTime = root.GetProperty("endTime").GetDateTimeOffset();
double summaryDuration = root.GetProperty("summary").GetProperty("totalDurationMs").GetDouble();
double expectedSummaryDuration = (reportEndTime - reportStartTime).TotalMilliseconds;

Assert.HasCount(2, testDurations);
Assert.IsLessThan(testEndTimes.Min(), testStartTimes.Max(), "Expected the two test execution intervals to overlap.");
Assert.IsLessThanOrEqualTo(
1d,
Math.Abs(expectedSummaryDuration - summaryDuration),
$"Expected summary duration to match the report's wall-clock interval. Summary: {summaryDuration} ms; interval: {expectedSummaryDuration} ms; sum of tests: {testDurations.Sum()} ms.");
}

[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
[TestMethod]
public async Task Html_WhenReportHtmlFilenameIsSpecified_HtmlReportIsGeneratedWithThatName(string tfm)
Expand Down Expand Up @@ -194,6 +242,9 @@ public static async Task<int> Main(string[] args)

public class DummyTestFramework : ITestFramework, IDataProducer
{
private readonly TaskCompletionSource<bool> _parallelTestsReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _parallelTestsReadyCount;

public string Uid => nameof(DummyTestFramework);
public string Version => "2.0.0";
public string DisplayName => nameof(DummyTestFramework);
Expand All @@ -210,6 +261,15 @@ public Task<CloseTestSessionResult> CloseTestSessionAsync(CloseTestSessionContex

public async Task ExecuteRequestAsync(ExecuteRequestContext context)
{
if (Environment.GetEnvironmentVariable("PARALLELTESTS") == "1")
{
await Task.WhenAll(
RunParallelTestAsync(context, "parallel-test-1", "ParallelTest1"),
RunParallelTestAsync(context, "parallel-test-2", "ParallelTest2"));
context.Complete();
return;
}

await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(
context.Request.Session.SessionUid,
new TestNode()
Expand Down Expand Up @@ -257,6 +317,35 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context)

context.Complete();
}

private async Task RunParallelTestAsync(ExecuteRequestContext context, string uid, string displayName)
{
DateTimeOffset start = DateTimeOffset.UtcNow;
if (Interlocked.Increment(ref _parallelTestsReadyCount) == 2)
{
_parallelTestsReady.SetResult(true);
}

Task completedTask = await Task.WhenAny(_parallelTestsReady.Task, Task.Delay(TimeSpan.FromSeconds(30)));
if (completedTask != _parallelTestsReady.Task)
{
throw new TimeoutException("Parallel tests did not reach the rendezvous.");
}

await Task.Delay(TimeSpan.FromSeconds(1));
DateTimeOffset end = DateTimeOffset.UtcNow;

await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(
context.Request.Session.SessionUid,
new TestNode()
{
Uid = uid,
DisplayName = displayName,
Properties = new PropertyBag(
PassedTestNodeStateProperty.CachedInstance,
new TimingProperty(new TimingInfo(start, end, end - start))),
}));
}
}
""";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public async Task ProcessAsync_WithTwoInputs_WritesMergedReport()
Assert.AreEqual(2, (int?)summary["total"]);
Assert.AreEqual(1, (int?)summary["passed"]);
Assert.AreEqual(1, (int?)summary["failed"]);
Assert.AreEqual(30d, (double?)summary["totalDurationMs"]);
Assert.AreEqual(7_200_000d, (double?)summary["totalDurationMs"]);
Assert.AreSequenceEqual(
new[] { "first.html", "second.html" },
Directory.GetFiles(directory, "*.html").Select(Path.GetFileName).OrderBy(name => name, StringComparer.Ordinal));
Expand Down Expand Up @@ -961,7 +961,7 @@ public async Task ProcessAsync_ForRetryAttempts_DoesNotDoubleCountLogicalTotals(
Assert.AreEqual(3, (int?)summary["passed"]);
Assert.AreEqual(0, (int?)summary["failed"]);
Assert.AreEqual(1, (int?)summary["flaky"]);
Assert.AreEqual(33, (double?)summary["totalDurationMs"]);
Assert.AreEqual(180_000d, (double?)summary["totalDurationMs"]);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ public async Task GenerateReportAsync_WritesValidHtml_WithEmbeddedJson()
Assert.Contains("\"skipped\":1", html);
}

[TestMethod]
public async Task GenerateReportAsync_UsesWallClockDurationForSummary()
{
DateTimeOffset startTime = new(2026, 8, 31, 12, 0, 0, TimeSpan.Zero);
DateTimeOffset endTime = startTime.AddSeconds(5);
_ = _clockMock.SetupGet(clock => clock.UtcNow).Returns(endTime);
using var memoryStream = new MemoryFileStream();
HtmlReportEngine engine = CreateEngine(memoryStream, testStartTime: startTime);
CapturedTestResult[] tests =
[
Captured("a", "A", "passed", TimeSpan.FromSeconds(4)),
Captured("b", "B", "passed", TimeSpan.FromSeconds(4)),
];

await engine.GenerateReportAsync(tests);

JsonObject report = JsonNode.Parse(HtmlReportEngine.ExtractReportJson(memoryStream.GetUtf8Content()))!.AsObject();
Assert.AreEqual(5_000d, (double)report["summary"]!["totalDurationMs"]!);
}

[TestMethod]
public async Task GenerateReportAsync_WhenRecoveredAfterCrash_MarksReportIncomplete()
{
Expand Down Expand Up @@ -96,6 +116,33 @@ public void Merge_WhenAnyInputIsIncomplete_PropagatesRecoveryMetadata(bool colla
Assert.AreEqual("aborted", (string?)report["runStatus"]);
}

[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void Merge_UsesOverallWallClockDurationForSummary(bool collapseRetryAttempts)
{
DateTimeOffset startTime = new(2026, 8, 31, 12, 0, 0, TimeSpan.Zero);
string first = BuildMergeInput(
"shared",
incomplete: false,
startTime,
startTime.AddSeconds(5),
TimeSpan.FromSeconds(30));
string second = BuildMergeInput(
"shared",
incomplete: false,
startTime.AddSeconds(2),
startTime.AddSeconds(9),
TimeSpan.FromSeconds(40));

string merged = HtmlReportMerger.Merge(
[first, second],
collapseRetryAttempts ? HtmlMergeMode.CollapseRetryAttempts : HtmlMergeMode.Concatenate);
JsonObject report = JsonNode.Parse(HtmlReportEngine.ExtractReportJson(merged))!.AsObject();

Assert.AreEqual(9_000d, (double)report["summary"]!["totalDurationMs"]!);
}

[TestMethod]
public async Task GenerateReportAsync_EscapesScriptInjection_InDisplayName()
{
Expand Down Expand Up @@ -713,8 +760,15 @@ private static CapturedTestResult Captured(string uid, string name, string outco
ErrorMessage = errorMessage,
};

private static string BuildMergeInput(string uid, bool incomplete)
private static string BuildMergeInput(
string uid,
bool incomplete,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
TimeSpan? testDuration = null)
{
startTime ??= new DateTimeOffset(2026, 8, 31, 12, 0, 0, TimeSpan.Zero);
endTime ??= startTime.Value.AddSeconds(1);
var report = new JsonObject
{
["schemaVersion"] = "1",
Expand All @@ -726,15 +780,15 @@ private static string BuildMergeInput(string uid, bool incomplete)
["framework"] = "framework",
["frameworkUid"] = "framework",
["frameworkVersion"] = "1.0.0",
["startTime"] = "2026-08-31T12:00:00.0000000+00:00",
["endTime"] = "2026-08-31T12:00:01.0000000+00:00",
["startTime"] = startTime.Value.ToString("O", CultureInfo.InvariantCulture),
["endTime"] = endTime.Value.ToString("O", CultureInfo.InvariantCulture),
["exitCode"] = incomplete ? 1 : 0,
["tests"] = new JsonArray(new JsonObject
{
["uid"] = uid,
["displayName"] = uid,
["outcome"] = "passed",
["durationMs"] = 1,
["durationMs"] = (testDuration ?? TimeSpan.FromMilliseconds(1)).TotalMilliseconds,
}),
["summary"] = new JsonObject(),
};
Expand All @@ -747,15 +801,18 @@ private static string BuildMergeInput(string uid, bool incomplete)
return HtmlReportEngine.RenderReport(report.ToJsonString());
}

private HtmlReportEngine CreateEngine(MemoryFileStream stream, bool isIncomplete = false)
private HtmlReportEngine CreateEngine(
MemoryFileStream stream,
bool isIncomplete = false,
DateTimeOffset? testStartTime = null)
{
_ = _fileSystem.Setup(x => x.ExistFile(It.IsAny<string>())).Returns(false);
_ = _fileSystem.Setup(x => x.NewFileStream(It.IsAny<string>(), It.IsAny<FileMode>())).Returns(stream);

return CreateEngine(isIncomplete);
return CreateEngine(isIncomplete, testStartTime);
}

private HtmlReportEngine CreateEngine(bool isIncomplete = false)
private HtmlReportEngine CreateEngine(bool isIncomplete = false, DateTimeOffset? testStartTime = null)
{
_ = _configurationMock.SetupGet(_ => _[It.IsAny<string>()]).Returns(string.Empty);
_ = _environmentMock.SetupGet(_ => _.MachineName).Returns("MachineName");
Expand All @@ -773,7 +830,7 @@ private HtmlReportEngine CreateEngine(bool isIncomplete = false)
_configurationMock.Object,
_clockMock.Object,
_testFrameworkMock.Object,
DateTimeOffset.UtcNow,
testStartTime ?? DateTimeOffset.UtcNow,
0,
CancellationToken.None,
IsIncomplete: isIncomplete));
Expand Down
Loading