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
373 changes: 373 additions & 0 deletions docs/decisions/ctrf-03-assertion-failures.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ An MTP extension (`Microsoft.Testing.Extensions.CrashDump`) that automatically c

### CtrfReport

An MTP extension (`Microsoft.Testing.Extensions.CtrfReport`) that generates a [CTRF](https://github.com/ctrf-io/ctrf) (Common Test Report Format) JSON report at the end of a test run. CTRF is a vendor-neutral open standard for structured test results, consumed by GitHub Actions test-summary tools, Slack/Teams notifiers, dashboards, and other CI tooling. The reporter emits `specVersion: 0.2.0`, including native final-attempt identities in `tests[].attemptId`, and preserves legacy attempt identities when merging older reports. Enable via `--report-ctrf`; override the output filename with `--report-ctrf-filename`. When using [MSTest.Sdk](#mstestsdk), opt in with `<EnableMicrosoftTestingExtensionsCtrfReport>true</EnableMicrosoftTestingExtensionsCtrfReport>`. The stable producer uses the same package version as MTP and preserves its API, CLI, and documented 0.2.0 semantics within that major version; this does not guarantee framework UID stability or make producer-specific diagnostic metadata a stable protocol. See the [package compatibility policy](../src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md#compatibility).
An MTP extension (`Microsoft.Testing.Extensions.CtrfReport`) that generates a [CTRF](https://github.com/ctrf-io/ctrf) (Common Test Report Format) JSON report at the end of a test run. CTRF is a vendor-neutral open standard for structured test results, consumed by GitHub Actions test-summary tools, Slack/Teams notifiers, dashboards, and other CI tooling. The next-major reporter emits `specVersion: 0.3.0`, including attempt-local `assertionFailures` with available formatted expected/actual comparisons. It retains native final-attempt identities in `tests[].attemptId` and preserves legacy attempt identities when merging older reports. Enable via `--report-ctrf`; override the output filename with `--report-ctrf-filename`. When using [MSTest.Sdk](#mstestsdk), opt in with `<EnableMicrosoftTestingExtensionsCtrfReport>true</EnableMicrosoftTestingExtensionsCtrfReport>`. The producer uses the same package version as MTP; the stable 2.x line retains its documented 0.2.0 semantics. This does not guarantee framework UID stability or make producer-specific diagnostic metadata a stable protocol. See the [package compatibility policy](../src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md#compatibility).

## D

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ internal sealed class CapturedTestResult : CapturedTestResultBase
// (e.g. "timedOut", "errored", "cancelled"). Surfaced via CTRF `rawStatus`.
public string? RawStatus { get; init; }

public string? Expected { get; init; }

public string? Actual { get; init; }

public string? Namespace { get; init; }

public string? FilePath { get; init; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ private static void WriteTest(Utf8JsonWriter writer, ReportTestResult result, st
writer.WriteString("trace", r.StackTrace);
}

WriteAssertionFailure(writer, r);

if (r.FilePath is not null)
{
writer.WriteString("filePath", r.FilePath);
Expand Down Expand Up @@ -233,6 +235,8 @@ private static void WriteRetryAttempt(Utf8JsonWriter writer, CapturedTestResult
writer.WriteString("trace", attempt.StackTrace);
}

WriteAssertionFailure(writer, attempt);

if (attempt.Line is { } line)
{
writer.WriteNumber("line", line);
Expand Down Expand Up @@ -262,6 +266,30 @@ private static void WriteRetryAttempt(Utf8JsonWriter writer, CapturedTestResult
writer.WriteEndObject();
}

private static void WriteAssertionFailure(Utf8JsonWriter writer, CapturedTestResult result)
{
if (result.Status != "failed" || (result.Expected is null && result.Actual is null))
{
return;
}

writer.WritePropertyName("assertionFailures");
writer.WriteStartArray();
writer.WriteStartObject();
if (result.Expected is not null)
{
writer.WriteString("expected", result.Expected);
}

if (result.Actual is not null)
{
writer.WriteString("actual", result.Actual);
}

writer.WriteEndObject();
writer.WriteEndArray();
}

private static bool HasSameKeyEarlier(IReadOnlyList<KeyValuePair<string, string>> traits, int index)
{
string key = traits[index].Key;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ internal sealed partial class CtrfReportEngine : ReportEngineBase
// CTRF spec: https://github.com/ctrf-io/ctrf
private const string CtrfReportFormat = "CTRF";
// Pre-1.0 MINOR releases may be incompatible, so review the mapping before updating this pinned version.
private const string CtrfSpecVersion = "0.2.0";
private const string CtrfSpecVersion = "0.3.0";

public CtrfReportEngine(ReportEngineContext context)
: base(context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,16 @@ private static bool TryReadLong(JsonNode node, string propertyName, out long val
/// non-cryptographic 128-bit FNV-1a fill is sufficient here — the id only needs to be deterministic and
/// collision-resistant enough to identify a merged report, not secret.
/// </summary>
private static string CreateDeterministicReportId(IReadOnlyList<string> acceptedReports, CtrfMergeMode mode, bool isSpecVersionPromoted)
private static string CreateDeterministicReportId(IReadOnlyList<string> acceptedReports, CtrfMergeMode mode, string? formatVersion)
{
// Schema promotion also changes the document and must not reuse its pre-promotion identity.
string formatDiscriminator = isSpecVersionPromoted
? "microsoft.testingplatform.lineage.v1.specVersion0.2.0"
: "microsoft.testingplatform.lineage.v1";
// The released 0.3.0 projection preserves more fields than the draft projection.
// Keep the existing discriminators for older formats.
string formatDiscriminator = formatVersion switch
{
"0.3.0" => "microsoft.testingplatform.lineage.v1.specVersion0.3.0.release",
not null => $"microsoft.testingplatform.lineage.v1.specVersion{formatVersion}",
_ => "microsoft.testingplatform.lineage.v1",
};
return CreateDeterministicId([formatDiscriminator, .. acceptedReports], (ulong)mode).ToString("D");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ internal static partial class CtrfReportMerger
"duration",
"message",
"trace",
"assertionFailures",
"line",
"snippet",
"stdout",
Expand All @@ -43,7 +44,7 @@ internal static partial class CtrfReportMerger
/// than a sum across attempts. Attempts an input already recorded in its own <c>retryAttempts[]</c> (in-process
/// retries within a single attempt process) are flattened into the same history so no execution is lost.
/// </remarks>
private static JsonArray CollapseRetryAttempts(IReadOnlyList<IReadOnlyList<JsonObject>> reports)
private static JsonArray CollapseRetryAttempts(IReadOnlyList<IReadOnlyList<JsonObject>> reports, bool supportsRetryThreadId)
{
var ambiguousIdentities = new HashSet<string>(StringComparer.Ordinal);
var ambiguousLifecycles = new HashSet<(string TestIdentity, string ExecutionId)>();
Expand Down Expand Up @@ -135,7 +136,7 @@ private static JsonArray CollapseRetryAttempts(IReadOnlyList<IReadOnlyList<JsonO
var collapsed = new JsonArray();
foreach ((JsonObject final, List<JsonObject> priors) in slots)
{
collapsed.Add(BuildCollapsedTest(final, priors));
collapsed.Add(BuildCollapsedTest(final, priors, supportsRetryThreadId));
}

return collapsed;
Expand Down Expand Up @@ -218,7 +219,7 @@ private static JsonArray CollapseRetryAttempts(IReadOnlyList<IReadOnlyList<JsonO
return identity.ToString();
}

private static JsonNode BuildCollapsedTest(JsonObject final, List<JsonObject> priors)
private static JsonNode BuildCollapsedTest(JsonObject final, List<JsonObject> priors, bool supportsRetryThreadId)
{
var collapsed = (JsonObject)final.DeepClone();

Expand All @@ -234,13 +235,13 @@ private static JsonNode BuildCollapsedTest(JsonObject final, List<JsonObject> pr
var history = new JsonArray();
foreach (JsonObject prior in priors)
{
AppendAttempts(history, prior);
AppendAttempts(history, prior, supportsRetryThreadId);
}

// In-process retries observed by the final attempt precede its own outcome in the history.
if (collapsed["retryAttempts"] is JsonArray finalAttempts)
{
AppendNestedAttempts(history, finalAttempts);
AppendNestedAttempts(history, finalAttempts, supportsRetryThreadId);
}

bool anyFailed = false;
Expand Down Expand Up @@ -276,14 +277,14 @@ private static JsonNode BuildCollapsedTest(JsonObject final, List<JsonObject> pr
/// Appends the executions a non-final attempt row represents — the attempts it already nested, then its own
/// outcome — to the retry history being built.
/// </summary>
private static void AppendAttempts(JsonArray history, JsonObject test)
private static void AppendAttempts(JsonArray history, JsonObject test, bool supportsRetryThreadId)
{
if (test["retryAttempts"] is JsonArray nested)
{
AppendNestedAttempts(history, nested);
AppendNestedAttempts(history, nested, supportsRetryThreadId);
}

history.Add(ToRetryAttempt(test));
history.Add(ToRetryAttempt(test, supportsRetryThreadId));
}

/// <summary>
Expand All @@ -292,13 +293,13 @@ private static void AppendAttempts(JsonArray history, JsonObject test)
/// wrong-typed status or a disallowed field into the merged history. Entries that are not objects are skipped:
/// they could not describe an execution.
/// </summary>
private static void AppendNestedAttempts(JsonArray history, JsonArray nested)
private static void AppendNestedAttempts(JsonArray history, JsonArray nested, bool supportsRetryThreadId)
{
foreach (JsonNode? attempt in nested)
{
if (attempt is JsonObject attemptObject)
{
history.Add(ToRetryAttempt(attemptObject));
history.Add(ToRetryAttempt(attemptObject, supportsRetryThreadId));
}
}
}
Expand All @@ -308,7 +309,7 @@ private static void AppendNestedAttempts(JsonArray history, JsonArray nested)
/// fields than a test: everything else (name, suite, tags, labels, ...) either belongs to the collapsed test
/// object or, like <c>rawStatus</c>, moves under <c>extra</c>, the only permitted extension point.
/// </summary>
private static JsonNode ToRetryAttempt(JsonObject test)
private static JsonNode ToRetryAttempt(JsonObject test, bool supportsRetryThreadId)
{
// 'attempt' is assigned by the caller, once the position of this execution in the history is known.
var attempt = new JsonObject
Expand All @@ -328,6 +329,11 @@ private static JsonNode ToRetryAttempt(JsonObject test)
attempt["attemptId"] = attemptId;
}

if (supportsRetryThreadId && ReadString(test, "threadId") is string threadId)
{
attempt["threadId"] = threadId;
}

foreach (string field in RetryAttemptFields)
{
if (test[field] is JsonNode value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ namespace Microsoft.Testing.Extensions.CtrfReport;
/// TRX and JUnit mergers, demonstrating that the same post-processing shape fits a JSON format:
/// <list type="bullet">
/// <item><description><c>results.tests[]</c> arrays are concatenated, except that elements which are not Test objects are dropped so one input's malformed row cannot invalidate the merged document; <see cref="CtrfMergeMode.CollapseRetryAttempts"/> additionally folds successive attempts of the same test into one row.</description></item>
/// <item><description>For 0.3.0 output, <c>results.errors[]</c> objects are concatenated in input order without deduplication; malformed error arrays are rejected.</description></item>
/// <item><description><c>results.summary</c> counters are re-derived by counting the merged <c>tests[]</c> (so <c>summary.tests</c> always matches the array length); <c>start</c>/<c>stop</c> use the earliest/latest across inputs, <c>duration</c> is the resulting span.</description></item>
/// <item><description><c>reportFormat</c> is taken from the first report. A 0.2.0 input promotes compatible earlier inputs to <c>specVersion</c> 0.2.0; unreviewed version mixtures are rejected. Otherwise the first report's version is retained. <c>reportId</c> is derived deterministically from the inputs, merge mode and schema promotion, so identical inputs reproduce the same id (RFC 018 idempotency) while materially different documents get distinct ids.</description></item>
/// <item><description><c>reportFormat</c> is taken from the first report. A 0.3.0 input promotes compatible earlier inputs to <c>specVersion</c> 0.3.0; otherwise a 0.2.0 input promotes compatible earlier inputs to 0.2.0. Unreviewed version mixtures are rejected. Otherwise the first report's version is retained. <c>reportId</c> is derived deterministically from the inputs, merge mode and output format, so identical inputs reproduce the same id (RFC 018 idempotency) while materially different documents get distinct ids.</description></item>
/// <item><description><c>runId</c> is carried over when every input agrees on one, because the merged document describes the same logical run as its inputs while remaining a distinct artifact with its own <c>reportId</c> (see ctrf-io/ctrf#58).</description></item>
/// <item><description><c>tool</c> keeps a concrete identity only when every input reported the exact same tool object; otherwise (inputs disagree or any input omits it) a neutral merger identity is used, so one framework is not attributed to another's tests.</description></item>
/// <item><description><c>environment</c> keeps the first report's shared fields, but module-specific values under <c>extra</c> (<c>testApplication</c>, <c>exitCode</c>) are dropped rather than presented as describing all merged modules.</description></item>
Expand Down Expand Up @@ -72,6 +73,8 @@ private static string Merge(

JsonObject? first = null;
var mergedTests = new JsonArray();
var mergedErrors = new JsonArray();
bool hasMalformedRunErrors = false;
var retryReports = new List<IReadOnlyList<JsonObject>>();

// Accumulate the raw JSON of every ACCEPTED CTRF input so the deterministic reportId is derived only
Expand Down Expand Up @@ -159,6 +162,28 @@ private static string Merge(
}

JsonNode? results = root["results"];
if (results is JsonObject resultsNode && resultsNode.TryGetPropertyValue("errors", out JsonNode? errors))
{
if (errors is JsonArray errorArray)
{
foreach (JsonNode? error in errorArray)
{
if (error is JsonObject errorObject)
{
mergedErrors.Add(errorObject.DeepClone());
}
else
{
hasMalformedRunErrors = true;
}
}
}
else
{
hasMalformedRunErrors = true;
}
}

var reportTests = new List<JsonObject>();
if (results?["tests"] is JsonArray testArray)
{
Expand Down Expand Up @@ -236,24 +261,31 @@ private static string Merge(
throw new ArgumentException("None of the provided inputs were valid CTRF reports.", nameof(inputReports));
}

// 0.2.0 only adds optional Test.attemptId to the schema used by our earlier reports.
// 0.3.0 adds optional assertion failures; 0.2.0 added optional Test.attemptId.
// Do not infer compatibility across other pre-1.0 releases or undeclared versions.
bool useVersion02 = specVersions.Contains("0.2.0");
if (useVersion02 && specVersions.Any(version => version is not ("0.0.0" or "0.0.4" or "0.1.0" or "0.2.0")))
string? reviewedSpecVersion = specVersions.Contains("0.3.0")
? "0.3.0"
: specVersions.Contains("0.2.0") ? "0.2.0" : null;
if (reviewedSpecVersion is not null && specVersions.Any(version => version is not ("0.0.0" or "0.0.4" or "0.1.0" or "0.2.0" or "0.3.0")))
{
throw new ArgumentException(
"CTRF 0.2.0 reports can only be merged with specification versions 0.0.0, 0.0.4, 0.1.0 or 0.2.0.",
$"CTRF {reviewedSpecVersion} reports can only be merged with specification versions 0.0.0, 0.0.4, 0.1.0, 0.2.0 or 0.3.0.",
invalidInputParameterName);
}

if (reviewedSpecVersion == "0.3.0" && hasMalformedRunErrors)
{
throw new ArgumentException("CTRF 0.3.0 run-level errors must be an array of objects.", invalidInputParameterName);
}

long startMs = earliestStart ?? 0;
long stopMs = latestStop ?? startMs;

// In retry mode the inputs are successive attempts of the same suite, so the same logical test can
// appear in several of them. Collapse those repeats into one row before counting, otherwise the same
// test would be reported (and counted) several times.
JsonArray tests = mode == CtrfMergeMode.CollapseRetryAttempts
? CollapseRetryAttempts(retryReports)
? CollapseRetryAttempts(retryReports, supportsRetryThreadId: reviewedSpecVersion == "0.3.0")
: mergedTests;

// Counters are derived from the merged tests[] rather than trusting each input's summary, so
Expand Down Expand Up @@ -331,15 +363,21 @@ private static string Merge(
}

resultsObject["tests"] = tests;
if (reviewedSpecVersion == "0.3.0" && mergedErrors.Count > 0)
{
resultsObject["errors"] = mergedErrors;
}

var merged = new JsonObject
{
["reportFormat"] = first["reportFormat"]?.DeepClone() ?? "CTRF",
["specVersion"] = useVersion02 ? "0.2.0" : first["specVersion"]?.DeepClone() ?? "0.0.0",
["specVersion"] = reviewedSpecVersion is not null ? reviewedSpecVersion : first["specVersion"]?.DeepClone() ?? "0.0.0",
["reportId"] = CreateDeterministicReportId(
acceptedReports,
mode,
isSpecVersionPromoted: useVersion02 && ReadString(first, "specVersion") != "0.2.0"),
formatVersion: reviewedSpecVersion == "0.3.0" || (reviewedSpecVersion is not null && ReadString(first, "specVersion") != reviewedSpecVersion)
? reviewedSpecVersion
: null),
};

// A merged document is a new artifact (hence its own reportId) but it still describes the same logical
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#nullable enable
Microsoft.Testing.Extensions.CtrfReport.CapturedTestResult.Actual.get -> string?
Microsoft.Testing.Extensions.CtrfReport.CapturedTestResult.Actual.init -> void
Microsoft.Testing.Extensions.CtrfReport.CapturedTestResult.Expected.get -> string?
Microsoft.Testing.Extensions.CtrfReport.CapturedTestResult.Expected.init -> void
const Microsoft.Testing.Platform.Helpers.EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTORCHESTRATORCHAIN = "TESTINGPLATFORM_TESTHOSTORCHESTRATORCHAIN" -> string!
static Microsoft.Testing.Platform.OutputDevice.TargetFrameworkParser.GetTargetFrameworkFromAssembly(System.Reflection.Assembly? entryAssembly) -> string?
Loading
Loading