diff --git a/docs/decisions/ctrf-03-assertion-failures.md b/docs/decisions/ctrf-03-assertion-failures.md new file mode 100644 index 0000000000..8e559c8e96 --- /dev/null +++ b/docs/decisions/ctrf-03-assertion-failures.md @@ -0,0 +1,373 @@ +# CTRF 0.3 assertion failures + +## Problem and contract + +The next major version of `Microsoft.Testing.Extensions.CtrfReport` adopts the +CTRF 0.3.0 format by default. This is a user-directed next-major change, not a +format change to the stable 2.x contract described in +[the stable-release decision](ctrf-stable-release.md). + +Capture the single comparison available from MTP's `AssertionFailureProperty` +and emit one `assertionFailures` entry on the failed attempt that owns it. +The explicit property is authoritative; only its absence permits the legacy +`Exception.Data["assert.expected"]` / `["assert.actual"]` string fallback. +Unavailable sides are omitted, while empty strings remain present. Do not parse +messages, invent typed values, or attach combined diagnostics to an individual +assertion. Existing result-level `message` and `trace` remain unchanged. + +The capture and crash-recovery journal retain bounded comparison text. Normal +reports, recovered reports, in-process retry history, and cross-process retry +merges preserve its association with the correct test and attempt. A later +passing result does not inherit an earlier failure's comparison. + +The existing MTP host owns execution, cancellation, disposal, and recovery. +There is no new handshake, CLI switch, registration API, or dependency. +Reporting remains opt-in; enabling it does not change test outcomes or exits. +Multiple-assertion transport is outside this change: MSTest continues to omit +an ambiguous result-level pair when more than one comparison exists. + +## Research and experiments + +2026-11-10, baseline `32a6ed6e1511ae9b61c9ce307e22ed5594b239cc`: + +- The [maintainer's reply][reply] specifies optional, non-empty + `assertionFailures` collections on final results and earlier attempts, with + producer-formatted strings and independently optional comparison sides. +- [ctrf-io/ctrf#87][proposal] is open, not a released specification. The reviewed + immutable proposal snapshot is + `c109525a7567a629667ebbcdce1c03bdf7c79ab7`; upstream main and its latest tag + still identify 0.2.0. This implementation targets that proposed 0.3.0 contract. + Final upstream schema alignment is a release dependency, not claimed complete. +- A recursive schema comparison against v0.2.0 + (`e325eb33c7662a208bfa4d093a41cc55439d6e6a`), excluding descriptive text, + found only the new optional assertion collections on Test and retry entries. + Both object schemas reject unknown properties, so adding the field while + continuing to declare 0.2.0 would be invalid. +- The current CTRF capture DTO and writer discard comparison data. The retry + merger's field whitelist would also discard the new collection when a final + result or an existing nested attempt is projected into earlier history. +- MSTest already supplies an unambiguous single comparison through MTP. + Its multiple-comparison suppression is deliberate and need not change. +- The pinned SDK bootstrap and existing CTRF unit baseline succeeded: + 212 executed and passed on net10.0, with 32 method-level workers and no skips. +- The implementation built for netstandard2.0, net10.0 and net11.0 with no + warnings or errors. A subsequent all-source build/pack succeeded, including + package content and metadata validation. The aligned local package versions + are MTP/CTRF/Retry 3.0.0-dev and MSTest 5.0.0-dev. +- The isolated comparison is outside the repository tree and retains the new + DTO fields/API entries and 0.3.0 header while using the original capture, + writer and merger behavior. It is a buildable behavior-removal comparison, + not a pristine-baseline run. Its first pack failed because the local clone's + filesystem origin supplied no package project URL. Setting only that + comparison clone's origin to the real repository fixed package metadata; + repacking succeeded. That setup failure is not red-phase evidence. + +2026-11-26, released specification: + +- The annotated [v0.3.0 tag][release] points to + `6cafa1ebdf4d5286f6e208124d313269aa357411`. Comparing its schema directly + with the reviewed snapshot, excluding descriptions, found three additional + optional fields: root `provenance`, `results.errors`, and retry-attempt + `threadId`. The assertion-failure schemas are unchanged. +- The released specification says consumers must account for global errors and + recommends concatenating them when merging. The merger must retain those + errors and attempt-local thread IDs in 0.3.0 output; omitting the former + could make a run with infrastructure errors appear error-free. The 0.2.0 + retry schema does not allow attempt-level `threadId`, so older output must + remain unchanged. +- For a 0.3.0 merge, reject a run-error field that is not an array of objects + rather than silently dropping an unrepresentable error and producing a + success-shaped report. Legacy-only merges retain their existing handling. +- Native provenance is optional. The existing producer-specific lineage remains + diagnostic metadata; this change does not invent IDs for foreign inputs or + claim standardized provenance or input completeness. +- Before the release-alignment fix, the rebased source was + `d19e16fe4c1bb04919cf7aee42c26e4db5f8b5cb` with a retained regression-test + patch SHA-256 + `bca57fa94f41d9a4cc279d62f099bb10f14c666e5588551621f26e4ace959293`. + The pinned `12.0.100-alpha.1.26570.125` SDK built the net10.0 test project. + The single-TFM build required `/p:NoWarn=NU1510`: without it, NuGet reports + pre-existing `System.Text.Json` references in CTRF, HTML, and JUnit as + unnecessary and treats the warning as an error. +- The new focused unit selection executed eight cases before the fix: seven + failed at the intended assertions, exposing dropped run errors, dropped retry + thread IDs, and reuse of a draft-projection report ID. The remaining 0.2.0 + compatibility case passed. The runner exited 2 with no skipped cases. + +## Alternatives and decision + +Keep the current output: valid 0.2.0, but loses structured comparisons. +Use producer-specific `extra`: preserves data without the new schema, but +creates the interoperability fragmentation this upstream change resolves. +Add a format opt-in: unnecessary because the user confirmed that adoption is +for the next major package version. Chosen: native 0.3.0 by default. + +Retain only the available single comparison, rather than introducing a new +public collection API or trying to reconstruct the original exception tree. +Leave combined message/trace diagnostics on the enclosing result because they +may describe other failures as well as that comparison. + +The merger promotes reviewed 0.0.0/0.0.4/0.1.0/0.2.0 inputs when a 0.3.0 input +is present, independent of input order. Unknown or undeclared versions cannot +be mixed with a reviewed 0.2.0/0.3.0 report. Rejection preserves inputs and an +existing destination. Legacy-only version handling and 0.2.0 report identities +remain unchanged. The new 0.3.0 projection gets its own deterministic report-ID +discriminator so changed retry contents cannot reuse the old merger's identity. +The released projection uses a new discriminator from the draft projection too: +run errors and retry thread IDs change the document even with identical inputs. + +## Validation and demonstration + +### 2026-11-26 release alignment and final rebase + +The released-schema changes were tested on rebased commit +`df4a665a5f9d5054a208e939f19eab8dd839f1e8`, based on `main` at +`88543d4bc3d066319ab059a2f99c39e6a59bbf72`. The paired red runs used the +earlier rebase `d19e16fe4c1bb04919cf7aee42c26e4db5f8b5cb`, with the same +regression tests retained; that rebase preceded the additional `main` commit. +The released-schema unit-test patch has SHA-256 +`8B4570888E09196E0428F06C8616BA6F7186FA64CC1963E9CC5253EFA7B2F4AA`. +The final unit-test patch, including the malformed-error cases, has SHA-256 +`4918E2B586D12C4C338B6ADB4A2CF6ADEB7CC22C7F65F14B72B692CDCA2E090E`. +The red acceptance patch has SHA-256 +`02FA5D1BCF710C169F3A8A5DA6B0241149EDCCE4E2B74E68CB8A449B0D74CD55`; +its merger test and assertions match the green test. The additional malformed +error tests were first run against the intermediate release-aligned merger +before its invalid-error guard was added. + +| Test-value evidence | Without the relevant behavior | With the behavior | +| --- | --- | --- | +| Run errors, retry threads and released report identity: eight net10.0 unit cases | Seven failed at the missing-error, missing-thread or reused-ID assertions; the 0.2-only compatibility case passed. Exit 2. | The same eight passed; exit 0. | +| Malformed run errors: four net10.0 unit cases | Three failed because the expected exception was not thrown; the legacy-only case passed. Exit 2. | The same four passed; exit 0. | +| `Ctrf_MergingReleasedVersion_PreservesRunErrorsAndAttemptThreads` | The packed consumer executed and failed its assertion for the missing nested thread; exit 2. | The same test passed with the released errors and attempt threads; exit 0. | + +The red unit runs used the following selectors on the Debug net10.0 host; +the acceptance selector used the Release net12.0 host. Each results variable +identifies a fresh, task-owned directory. + +```powershell +$releaseFilter = 'FullyQualifiedName~Merge_Version03_PreservesRunErrorsInInputOrder|FullyQualifiedName~Merge_CollapseRetryAttempts_PreservesThreadIdsOnlyInVersion03|FullyQualifiedName~Merge_Version03_ReleasedProjectionDoesNotReuseDraftReportId' +$malformedFilter = 'FullyQualifiedName~Merge_Version03_WithMalformedRunErrors_Throws|FullyQualifiedName~Merge_Version02_IgnoresUnrecognizedRunErrors' +$mergerFilter = 'FullyQualifiedName~Ctrf_MergingReleasedVersion_PreservesRunErrorsAndAttemptThreads' + +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net10.0\Microsoft.Testing.Extensions.UnitTests.dll --filter $releaseFilter --report-trx --results-directory $redUnitResults +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net10.0\Microsoft.Testing.Extensions.UnitTests.dll --filter $malformedFilter --report-trx --report-trx-filename red-malformed.trx --results-directory $redMalformedResults +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Release\net12.0\Microsoft.Testing.Platform.Acceptance.IntegrationTests.dll --filter $mergerFilter --report-trx --report-trx-filename red-release.trx --results-directory $redAcceptanceResults +``` + +These are executed behavioral comparisons, not build, restore, launch or +zero-test failures. A separate acceptance-only reflection harness exercised +malformed errors with independently packed intermediate and final mergers: +the intermediate returned zero and replaced an existing output, whereas the +final consumer exited nonzero with the rejection message and preserved the +existing output. This is not a claim about a standard shipping CLI exit. + +On Windows, the pinned SDK `12.0.100-alpha.1.26570.125` built and packed the +rebased solution in Release. The following command passed with exit 0: + +```powershell +.\eng\build.ps1 -restore -build -pack -c Release -msbuildEngine vs -verbosity quiet '/p:EnableCodeCoverage=false' '/p:FastAcceptanceTest=true' '/warnnotaserror:NU1510' '/bl:{}' +``` + +An initial build without restore failed because prior single-target restores +left multi-target assets and localization imports incomplete +(`NETSDK1005` and missing `UpdateXlf`). The full restore and pack above +succeeded; that setup failure is not regression evidence. + +The following selectors and commands were run against the rebased Release +outputs. Each results variable identifies a fresh, task-owned directory; the +matching `--list-tests --filter` discovery ran separately before execution. +The outer acceptance hosts target net12.0; generated consumers use the packed +Release assets, including net11.0 and net462 where selected. + +```powershell +$evidence = Join-Path $env:TEMP ("ctrf-validation-" + [Guid]::NewGuid().ToString('N')) +$unitResults = Join-Path $evidence 'unit' +$broadResults = Join-Path $evidence 'broad' +$focusedResults = Join-Path $evidence 'focused' +$cache = Join-Path $evidence 'packages' +New-Item -ItemType Directory -Path $unitResults, $broadResults, $focusedResults, $cache | Out-Null +[IO.File]::WriteAllText((Join-Path $cache '.testfx-collection-cache'), 'testfx-collection-cache-v1') +$env:TESTFX_COLLECTION_NUGET_CACHE = $cache +$env:DOTNET_ROOT = (Resolve-Path '.\.dotnet').Path +$env:PATH = "$env:DOTNET_ROOT;$env:PATH" + +$unitFilter = 'FullyQualifiedName~Ctrf&FullyQualifiedName!~MergeToFileAsync_WhenOutputDiffersByCaseOnly_IsAllowedOnCaseSensitiveFilesystem' +$mtpFilter = 'FullyQualifiedName~Microsoft.Testing.Platform.Acceptance.IntegrationTests.CtrfReportTests|FullyQualifiedName~RetryFailedTestsTests.RetryFailedTests_CtrfReports_UseLogicalRunIdentityAndRecordLineage' +$mstestFilter = 'FullyQualifiedName~MSTest.Acceptance.IntegrationTests.CtrfReportTests|FullyQualifiedName~MSTest.Acceptance.IntegrationTests.CtrfReportRetryAttributeTests' +$sdkFilter = 'FullyQualifiedName~CtrfReport_UsesPlatformVersion_WhenOptedIn' + +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Release\net10.0\Microsoft.Testing.Extensions.UnitTests.dll --filter $unitFilter --report-trx --report-trx-filename broad.trx --results-directory $unitResults +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Release\net12.0\Microsoft.Testing.Platform.Acceptance.IntegrationTests.dll --filter $mtpFilter --report-trx --report-trx-filename mtp.trx --results-directory $broadResults +.\.dotnet\dotnet.exe exec artifacts\bin\MSTest.Acceptance.IntegrationTests\Release\net12.0\MSTest.Acceptance.IntegrationTests.dll --filter $mstestFilter --report-trx --report-trx-filename mstest.trx --results-directory $broadResults +.\.dotnet\dotnet.exe exec artifacts\bin\MSTest.Acceptance.IntegrationTests\Release\net12.0\MSTest.Acceptance.IntegrationTests.dll --filter $sdkFilter --report-trx --report-trx-filename sdk.trx --results-directory $focusedResults +``` + +The commands executed 296 unit, 27 MTP acceptance, three MSTest acceptance and +two SDK acceptance cases respectively; all passed with exit 0 and no skips. +The focused packed merger case also passed independently. Discovery and fresh +TRX identities were reconciled using the repository execution verifier. The +Windows-inapplicable case-sensitive-filesystem unit case was excluded. The +acceptance assembly used 32 method-level workers; existing shared-asset +exclusions remain, and the added merger case uses a GUID-owned directory. + +The final `Microsoft.Testing.Extensions.CtrfReport.3.0.0-dev.nupkg` SHA-256 is +`A44E9D47DCC09A975A1B310BD7BAF37FE22C3EA3A3E09D0CEB1F76B3C1CC489A`. +Four generated-consumer `project.assets.json` files matched its package +SHA-512, and four net11.0 consumer DLLs matched the packed payload SHA-256 +`DC9D88461955EEB5B178A63BAA3A02A1F28A8028DCE5BD59A9766AF1DA68CD55`. +The two merger inputs, merged report and two SDK reports all passed validation +with format checks against the immutable released 0.3.0 schema, SHA-256 +`D8765D80A8CF2E9E81611F5DB97497599F56949938255AE2BF4ACA84E234DD21`. +The merger case uses an acceptance-only entry point to load the packed DLL; +the broader retry cases exercise the actual packaged platform path. + +Raw logs and result files are retained locally and are not public links. This +is a nonvisual JSON contract; no hosted dashboard rendering, cross-platform +execution, NativeAOT execution or final-head CI result is claimed. + +### 2026-11-10 feature baseline (historical) + +The tested source is baseline +`32a6ed6e1511ae9b61c9ce307e22ed5594b239cc` plus the production/test patch with +SHA-256 `E1CFF3A03467ADBA174C0B269448E7B177F5F965E221019972ACD5E43FEC73EE`. +The identical retained test patch in both variants has SHA-256 +`7103DF337AC49EF696903A3A52FDF92070AA26636AAE1C350A719DE63E55481C`. +The comparison's DTO/header support patch has SHA-256 +`27475C6D1448C83BBA407FA2B94A584B5CDD629AEF1A14AB4661B128CC8B39A1`. + +The pinned SDK is `12.0.100-alpha.1.26556.115`; builds and packs use Debug. +The outer acceptance hosts target net12.0 through Arcade's `NetCurrent`. +Generated shipping-package consumers build Release and execute net11.0 and +net462 with `FastAcceptanceTest=true`. Source-generation variants also build +successfully; the selected consumer executions use reflection metadata. + +| Executed check | Correct implementation | Behavior-removal comparison | +| --- | --- | --- | +| Applicable CTRF units, net10.0 | 281 executed/passed; exit 0 | Same 281 executed: 54 intended failures, 227 passed; exit 2 | +| Applicable CTRF units, net11.0 | 281 executed/passed; exit 0 | Not repeated on this TFM | +| Applicable CTRF units, net462 / net472 | 278 / 278 executed/passed; exits 0 | Not repeated on these TFMs | +| Packed MTP CTRF consumers | 25 executed/passed; exit 0 | Same 25 executed: 12 intended failures, 13 passed; exit 2 | +| Packed MSTest consumers | 3 executed/passed; exit 0 | Same 3 executed: 3 intended failures; exit 2 | +| Immutable schemas with format checks | All 62 retained reports passed their declared 0.1.0, 0.2.0 or reviewed 0.3.0 schema | 54 reports retained; the legacy-first aggregate also demonstrated one schema-invalid output | + +Every selected case executed, with no skips. Source/data-row plans and separate +discovery were reconciled with fresh TRX records using the repository execution +verifier. The existing Windows-inapplicable +`MergeToFileAsync_WhenOutputDiffersByCaseOnly_IsAllowedOnCaseSensitiveFilesystem` +was explicitly excluded from the applicable unit selection. This was not a full +repository or cross-platform run. + +Both variants used independently packed CTRF binaries with version 3.0.0-dev: +the correct package has SHA-256 +`33CBD56B508FAA7FA399D889221AEB1C3557FF9BA06C9615BBB8B1FC3C8BC97D`; +the comparison has +`F7342F5E9E38D96F8043BB6E59E94495C1A220DFFC8820979F8CCDCED0AEA97C`. +Each variant's 42 resolved package references matched the current package +SHA-512 values in `project.assets.json`, and 60 generated-consumer output DLLs +matched the corresponding packed payloads. Effective feeds, marked per-variant +package caches, executable locations, reports, manifests, binlogs and TRX were +retained in session artifacts. The concise results here are the published +evidence; raw local logs are not claimed to be publicly accessible. +The isolated comparison source and outputs are retained locally for replay; +its borrowed-toolchain junction was removed after execution without changing the +original toolchain. All environment overrides were scoped to their commands. + +| Requirement / risk | Automated E2E evidence | Rendered check / gap | +| --- | --- | --- | +| Explicit comparisons, absent/empty sides and correct result identities | `Ctrf_WhenReportCtrfIsSpecified_CtrfReportIsGeneratedInDefaultLocation`, `Ctrf_WhenReportCtrfFilenameIsSpecified_CtrfReportIsGeneratedWithThatName`, and `CtrfReport_WhenTestsArePassingAndFailing_CtrfFileIsGeneratedWithBothOutcomes` passed. Assertions associate data with each named result and outcome, not only text presence. | Nonvisual JSON contract; no hosted dashboard rendering change. | +| Completed comparisons survive a host crash | `Ctrf_WhenTestHostCrashes_RecoversCompletedResultsAndMarksReportIncomplete` passed with the expected failed-child/crash exit and recovered pair. | Same JSON contract. | +| Earlier failures do not leak onto a passing final result | `CtrfReport_WithMSTestRetryAttribute_MarksRetriedTestAsFlaky` and `RetryFailedTests_CtrfReports_UseLogicalRunIdentityAndRecordLineage` passed, inspecting physical attempts, prior history and final results separately. | Same JSON contract. | +| Mixed schema versions and nested retry history remain correct | `Ctrf_MergingLegacyAndCurrentReports_PreservesVersionAndAttemptIdentities` passed all four .1/.2 input-order cases; unit cases below preserve ordered foreign arrays and nested attempts. | All actual green report documents passed the matching immutable schema. | + +### Test-value evidence + +| Contract / named cases | Without the behavior | Correct implementation | +| --- | --- | --- | +| Explicit/legacy precedence, null/empty semantics: `TestResultCapture_ExplicitComparison_RoundTripsOnlyKnownSides`, `TestResultCapture_ExplicitComparison_TakesPrecedenceOverLegacyData`, `TestResultCapture_LegacyComparison_UsesOnlyStringValues` | Executed: missing comparison assertions detected the original capture/writer behavior. | Same cases passed. | +| Failed-only capture, escaping, bounded strings: `TestResultCapture_NonFailedStates_OmitComparisonMetadata`, `TestResultCapture_ComparisonText_PreservesEscapedMultilineValues`, `TestResultCapture_ComparisonLimits_PreserveBoundaryAndSurrogates` | Executed: missing-data faults detected; intentional omission cases remained green. | Same cases passed, including independently bounded sides and surrogate boundaries. | +| Journal and in-process ownership: `ControllerChild_AssertionComparisonsSurviveJournalRoundTripAsync`, `TestResultCapture_InProcessRetries_KeepComparisonsWithOwningAttempt` | Executed: explicit assertionFailures presence assertions failed after the retained journal/retry setup ran. | Same cases passed through source-generated journal deserialization and ordered retry history. | +| Foreign arrays: `Merge_CollapseRetryAttempts_PreservesOrderedAssertionFailuresAndNestedHistory` | Executed: missing whitelist data detected in both final-pass/final-failure cases. | Both passed with ordered multi-entry/nested arrays and distinct final data. | +| Version/identity/file safety: `Merge_CompatibleSpecVersions_UsesVersion03`, `Merge_Version03WithUnreviewedSpecVersion_Throws`, `Merge_Version03_UsesDistinctDeterministicFormatIdentity`, `MergeToFileAsync_IncompatibleSpecVersions_PreservesInputsAndExistingOutput` | Executed: old negotiation, identity reuse and failure-to-reject were detected. | Same cases passed; existing exact 0.2.0 identity assertions also passed. | +| Real packaged report boundaries: the named E2E cases in the matrix above | Executed: 12 MTP and 3 MSTest outer assertions failed for absent comparisons, lost comparisons in recovery/retries, or incorrect mixed-version behavior. | All 28 outer cases passed. Multiple-comparison suppression remains unchanged and is additionally checked in the real MSTest consumer. | + +These are behavior-removal results, not compilation/setup failures. Initial +setup attempts caught a semicolon-list wrapper argument issue, a test-helper +parameter name triggering MSTEST0017, and an incorrect assumption that the outer +acceptance host targeted net11.0. Those were corrected before the successful +runs and are not counted as red proof. No analyzer suppression or production +workaround was introduced. + +Reproduction from the repository root, with the repo-local `.dotnet` prepended +to `PATH` and `DOTNET_ROOT`, and an owned `$evidence` directory: + +```powershell +.\eng\build.ps1 -restore -build -pack -projects 'src\**\*.csproj' -binaryLog '/bl:{}' /p:EnableCodeCoverage=false /p:FastAcceptanceTest=true + +$projects = @( + 'test\UnitTests\Microsoft.Testing.Extensions.UnitTests\Microsoft.Testing.Extensions.UnitTests.csproj', + 'test\IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj', + 'test\IntegrationTests\MSTest.Acceptance.IntegrationTests\MSTest.Acceptance.IntegrationTests.csproj' +) +foreach ($project in $projects) { + .\eng\build.ps1 -restore -build -projects $project -verbosity quiet -binaryLog '/bl:{}' /p:EnableCodeCoverage=false /p:FastAcceptanceTest=true + if ($LASTEXITCODE -ne 0) { throw "Build failed: $project" } +} + +$unitFilter = 'FullyQualifiedName~Ctrf&FullyQualifiedName!~MergeToFileAsync_WhenOutputDiffersByCaseOnly_IsAllowedOnCaseSensitiveFilesystem' +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net10.0\Microsoft.Testing.Extensions.UnitTests.dll --filter $unitFilter +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net11.0\Microsoft.Testing.Extensions.UnitTests.dll --filter $unitFilter +.\artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net462\Microsoft.Testing.Extensions.UnitTests.exe --filter $unitFilter +.\artifacts\bin\Microsoft.Testing.Extensions.UnitTests\Debug\net472\Microsoft.Testing.Extensions.UnitTests.exe --filter $unitFilter + +$mtpFilter = 'FullyQualifiedName~Microsoft.Testing.Platform.Acceptance.IntegrationTests.CtrfReportTests|FullyQualifiedName~RetryFailedTestsTests.RetryFailedTests_CtrfReports_UseLogicalRunIdentityAndRecordLineage' +.\.dotnet\dotnet.exe exec artifacts\bin\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Debug\net12.0\Microsoft.Testing.Platform.Acceptance.IntegrationTests.dll --filter $mtpFilter + +$mstestFilter = 'FullyQualifiedName~MSTest.Acceptance.IntegrationTests.CtrfReportTests|FullyQualifiedName~MSTest.Acceptance.IntegrationTests.CtrfReportRetryAttributeTests' +.\.dotnet\dotnet.exe exec artifacts\bin\MSTest.Acceptance.IntegrationTests\Debug\net12.0\MSTest.Acceptance.IntegrationTests.dll --filter $mstestFilter +``` + +All six execution commands passed. Recorded runs also supplied +`--report-trx --report-trx-filename .trx --results-directory `; +matching `--list-tests` commands passed before acceptance execution. Build and +pack commands used unique named binlogs. The same unit and acceptance selectors +ran against the separately built/packed comparison. The acceptance helpers +record their child build binlogs and assert expected child exits; a deliberately +failing test host exits 2, retry success and merge commands exit 0, and crash +recovery asserts `TestHostProcessExitedNonGracefully`. + +The actual packed MSTest report now associates this entry with `FailingTest`: + +```json +{ + "name": "FailingTest", + "status": "failed", + "assertionFailures": [ + { "expected": "1", "actual": "2" } + ] +} +``` + +The same comparison report lacks `assertionFailures`; both retain the enclosing +failure message and trace. This JSON transcript communicates the changed +nonvisual interchange contract better than a screenshot. No downstream +dashboard rendering or live CI run is claimed. + +Unit and acceptance assemblies retain method-level scheduling with CPU-count +workers (32 locally). New unit state is per-test mocks/memory or GUID-owned +files; journal workers are drained before disposal. The existing shared-asset +acceptance exclusions remain, and the MSTest CTRF asset class now declares the +same exclusion. CI selection was traced through the Windows Release +`TestFx.slnx` test step under `SkipTests=false`; no new category or execution +gate is required. CI execution itself remains unproven until the PR checks run. + +## Rollout and open questions + +Target the next major package only; no servicing backport or 2.x default-output +change is included. The CTRF extension owner remains responsible for rollout +and release-branch validation. Multiple-assertion transport remains a separate +enhancement. This change does not promise downstream dashboard support. + +[reply]: https://github.com/ctrf-io/ctrf/issues/67#issuecomment-6402490127 +[proposal]: https://github.com/ctrf-io/ctrf/pull/87 +[release]: https://github.com/ctrf-io/ctrf/tree/v0.3.0 diff --git a/docs/glossary.md b/docs/glossary.md index 2caf6786cb..1bcffa6314 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -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 `true`. 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 `true`. 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 diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CapturedTestResult.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CapturedTestResult.cs index b161f0d463..830c6a3464 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CapturedTestResult.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CapturedTestResult.cs @@ -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; } diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.JsonTestWriter.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.JsonTestWriter.cs index a7d6259a2f..b06f7948fc 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.JsonTestWriter.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.JsonTestWriter.cs @@ -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); @@ -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); @@ -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> traits, int index) { string key = traits[index].Key; diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.cs index 75f0cd7cb6..70eb760986 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportEngine.cs @@ -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) diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.JsonHelpers.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.JsonHelpers.cs index e7dd886f3e..602c0b4dc5 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.JsonHelpers.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.JsonHelpers.cs @@ -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. /// - private static string CreateDeterministicReportId(IReadOnlyList acceptedReports, CtrfMergeMode mode, bool isSpecVersionPromoted) + private static string CreateDeterministicReportId(IReadOnlyList 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"); } diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.RetryCollapsing.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.RetryCollapsing.cs index 8924be6131..e55973dadf 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.RetryCollapsing.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.RetryCollapsing.cs @@ -22,6 +22,7 @@ internal static partial class CtrfReportMerger "duration", "message", "trace", + "assertionFailures", "line", "snippet", "stdout", @@ -43,7 +44,7 @@ internal static partial class CtrfReportMerger /// than a sum across attempts. Attempts an input already recorded in its own retryAttempts[] (in-process /// retries within a single attempt process) are flattened into the same history so no execution is lost. /// - private static JsonArray CollapseRetryAttempts(IReadOnlyList> reports) + private static JsonArray CollapseRetryAttempts(IReadOnlyList> reports, bool supportsRetryThreadId) { var ambiguousIdentities = new HashSet(StringComparer.Ordinal); var ambiguousLifecycles = new HashSet<(string TestIdentity, string ExecutionId)>(); @@ -135,7 +136,7 @@ private static JsonArray CollapseRetryAttempts(IReadOnlyList priors) in slots) { - collapsed.Add(BuildCollapsedTest(final, priors)); + collapsed.Add(BuildCollapsedTest(final, priors, supportsRetryThreadId)); } return collapsed; @@ -218,7 +219,7 @@ private static JsonArray CollapseRetryAttempts(IReadOnlyList priors) + private static JsonNode BuildCollapsedTest(JsonObject final, List priors, bool supportsRetryThreadId) { var collapsed = (JsonObject)final.DeepClone(); @@ -234,13 +235,13 @@ private static JsonNode BuildCollapsedTest(JsonObject final, List 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; @@ -276,14 +277,14 @@ private static JsonNode BuildCollapsedTest(JsonObject final, List 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. /// - 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)); } /// @@ -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. /// - 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)); } } } @@ -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 rawStatus, moves under extra, the only permitted extension point. /// - 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 @@ -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) diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.cs index 6a54cbc336..c1769d54b3 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/CtrfReportMerger.cs @@ -14,8 +14,9 @@ namespace Microsoft.Testing.Extensions.CtrfReport; /// TRX and JUnit mergers, demonstrating that the same post-processing shape fits a JSON format: /// /// results.tests[] arrays are concatenated, except that elements which are not Test objects are dropped so one input's malformed row cannot invalidate the merged document; additionally folds successive attempts of the same test into one row. +/// For 0.3.0 output, results.errors[] objects are concatenated in input order without deduplication; malformed error arrays are rejected. /// results.summary counters are re-derived by counting the merged tests[] (so summary.tests always matches the array length); start/stop use the earliest/latest across inputs, duration is the resulting span. -/// reportFormat is taken from the first report. A 0.2.0 input promotes compatible earlier inputs to specVersion 0.2.0; unreviewed version mixtures are rejected. Otherwise the first report's version is retained. reportId 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. +/// reportFormat is taken from the first report. A 0.3.0 input promotes compatible earlier inputs to specVersion 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. reportId 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. /// runId 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 reportId (see ctrf-io/ctrf#58). /// tool 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. /// environment keeps the first report's shared fields, but module-specific values under extra (testApplication, exitCode) are dropped rather than presented as describing all merged modules. @@ -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>(); // Accumulate the raw JSON of every ACCEPTED CTRF input so the deterministic reportId is derived only @@ -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(); if (results?["tests"] is JsonArray testArray) { @@ -236,16 +261,23 @@ 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; @@ -253,7 +285,7 @@ private static string Merge( // 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 @@ -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 diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/InternalAPI/InternalAPI.Unshipped.txt b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/InternalAPI/InternalAPI.Unshipped.txt index 88504497d9..4b406c6fdb 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/InternalAPI/InternalAPI.Unshipped.txt @@ -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? diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md index 3ed9683a62..edf79f403d 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/PACKAGE.md @@ -14,14 +14,16 @@ dotnet add package Microsoft.Testing.Extensions.CtrfReport This package extends Microsoft.Testing.Platform with: -- **CTRF (Common Test Report Format) report**: a single JSON file conforming to the immutable [CTRF 0.2.0 schema](https://github.com/ctrf-io/ctrf/blob/v0.2.0/schema/ctrf.schema.json) that can be consumed by tools supporting that specification (dashboards, CI integrations, AI agents, etc.) without requiring a TRX or JUnit XML parser. +- **CTRF (Common Test Report Format) report**: a single JSON file using the [released CTRF 0.3.0 schema](https://github.com/ctrf-io/ctrf/blob/v0.3.0/schema/ctrf.schema.json) that can be consumed by tools supporting that specification (dashboards, CI integrations, AI agents, etc.) without requiring a TRX or JUnit XML parser. - **Cross-tool interoperability**: same shape as outputs produced by other testing frameworks that adopt CTRF, so results from multiple test runs can be aggregated by a single consumer. ## Compatibility -The stable 2.x package line supports the public registration API, existing CLI options, and documented CTRF 0.2.0 report semantics with backward compatibility. New execution reports remain pinned to the immutable 0.2.0 schema; a future upstream pre-1.0 specification is not adopted automatically. An incompatible schema or identity change requires a package major version or a separate explicit opt-in. Additive report fields must remain valid for the declared schema. +The stable 2.x package line retains its documented CTRF 0.2.0 report semantics. The next major package version adopts CTRF 0.3.0 by default, including structured assertion failures, while preserving the public registration API and existing CLI options. -This commitment does not make the upstream CTRF working draft immutable, add cross-run identity guarantees to framework-provided UIDs, or turn producer-specific `extra` metadata into a stable interchange protocol. The identity and merge limitations below still apply. +A future upstream pre-1.0 specification is not adopted automatically. An incompatible schema or identity change requires a package major version or a separate explicit opt-in. Additive report fields must remain valid for the declared schema. + +This commitment does not add cross-run identity guarantees to framework-provided UIDs or turn producer-specific `extra` metadata into a stable interchange protocol. The identity and merge limitations below still apply. The package uses the same version number and prerelease/final-release cadence as Microsoft.Testing.Platform. For example, the aligned final release produces version 2.6.0 of both packages. Prerelease builds remain prerelease; the normal final release produces stable packages with aligned stable platform dependencies. @@ -43,6 +45,20 @@ When using MSTest.Sdk, the extension remains opt-in and is not enabled by any pr ## Logical runs and retries +Failed attempts with an available structured comparison include one +`assertionFailures` entry containing producer-formatted `expected` and/or +`actual` strings. An unavailable side is omitted; an empty string remains a +valid value. The explicit MTP `AssertionFailureProperty` takes precedence over +the legacy exception-data keys. Comparison text follows the existing diagnostic +size limits and survives crash recovery. + +The collection belongs only to its own attempt: earlier failures stay in +`retryAttempts`, never on a later passing result. Overall `message` and `trace` +remain on the enclosing result rather than being attributed to an individual +assertion. When MSTest suppresses an ambiguous pair from multiple comparisons, +the reporter retains those diagnostics without inventing assertion entries. +The merger also preserves multiple entries supplied by other producers. + For exceptions with inner causes, the test's `trace` retains the full exception representation, including nested and aggregate-exception branches. The `message` continues to prefer the framework's explanation. Diagnostic text remains subject @@ -81,9 +97,11 @@ Producer-owned metadata lives under the root `extra["microsoft.testingplatform"] For nested merges, `inputs` identifies the immediate parent reports, not a flattened list of all physical executions. Retain those immutable reports to follow their lineage. Legacy or foreign reports may lack IDs or this extension metadata; do not infer lineage from matching test names or a shared `runId`. -When any input declares CTRF 0.2.0, the merged report also declares 0.2.0 regardless of input order. It accepts the reporter's historical 0.0.0 documents and the compatible 0.0.4/0.1.0 schema family alongside 0.2.0. Other or undeclared versions cannot be mixed with 0.2.0: the merge fails without overwriting its inputs or destination. Without a 0.2.0 input, the existing first-input version behavior is unchanged. Legacy final test objects retain their original identity fields; their optional native `attemptId` is not fabricated. +When any input declares CTRF 0.3.0, the merged report also declares 0.3.0 regardless of input order. It accepts the reporter's historical 0.0.0 documents and the compatible 0.0.4/0.1.0/0.2.0 schema family. Without a 0.3.0 input, a 0.2.0 input still promotes those compatible earlier reports to 0.2.0. Other or undeclared versions cannot be mixed with 0.2.0 or 0.3.0: the merge fails without overwriting its inputs or destination. Without either reviewed version, the existing first-input version behavior is unchanged. Legacy final test objects retain their original identity fields; their optional native `attemptId` is not fabricated. + +For 0.3.0 output, the merger retains run-level errors in input order without deduplicating them and preserves thread IDs on earlier retry attempts. A run-error field that is not an array of objects causes the merge to fail instead of silently dropping errors. It omits the optional standardized provenance field; the producer-specific lineage above does not imply input completeness. -A schema-promoted document gets a distinct deterministic `reportId` so it cannot be mistaken for the older merger's differently versioned output. Merging those same inputs again remains idempotent. +A schema-promoted document gets a distinct deterministic `reportId` so it cannot be mistaken for the older merger's differently versioned output. The new 0.3.0 projection uses a separate identity discriminator because it preserves additional retry fields. Existing 0.2.0 merge identities are unchanged. Merging those same inputs again remains idempotent. For aggregate analysis, consume the merged report instead of also counting the input reports it represents. Retain raw inputs for diagnostics. Do not deduplicate solely by `runId`, because independent module reports legitimately share it. When input identities are unavailable, select the aggregate explicitly rather than assuming every report in a directory is disjoint. @@ -93,7 +111,7 @@ Lineage is not proof of completeness. An input list records what contributed, no For comprehensive documentation, see . -For the versioned CTRF specification, see . +For the released CTRF specification, see . ## Feedback & contributing diff --git a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/TestResultCapture.cs b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/TestResultCapture.cs index 7f02c9b30c..83d082c6d6 100644 --- a/src/MTP/Microsoft.Testing.Extensions.CtrfReport/TestResultCapture.cs +++ b/src/MTP/Microsoft.Testing.Extensions.CtrfReport/TestResultCapture.cs @@ -31,12 +31,23 @@ internal static class TestResultCapture (string status, string? rawStatus) = ClassifyStatus(core.State); (string? ns, string? className, _) = GetClassAndMethodName(core.Properties.Identifier); RetryAttemptProperty? retryAttempt = node.Properties.SingleOrDefault(); + string? expected = null; + string? actual = null; + if (core.State is FailedTestNodeStateProperty failedState) + { + AssertionFailureProperty? assertionFailure = node.Properties.SingleOrDefault(); + // An explicit property is authoritative even when one side is unavailable. + expected = assertionFailure is not null ? assertionFailure.Expected : failedState.Exception?.Data["assert.expected"] as string; + actual = assertionFailure is not null ? assertionFailure.Actual : failedState.Exception?.Data["assert.actual"] as string; + } var result = new CapturedTestResult { TestId = CreateTestId(node.Uid.Value), Status = status, RawStatus = rawStatus, + Expected = TestResultCaptureHelper.Truncate(expected, TestResultCaptureHelper.MaxMessageLength), + Actual = TestResultCaptureHelper.Truncate(actual, TestResultCaptureHelper.MaxMessageLength), Namespace = TestResultCaptureHelper.Truncate(ns, TestResultCaptureHelper.MaxIdentityFieldLength), FilePath = TestResultCaptureHelper.Truncate(core.Properties.Location?.FilePath, TestResultCaptureHelper.MaxIdentityFieldLength), Line = core.Properties.Location?.LineSpan.Start.Line, diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CtrfReportTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CtrfReportTests.cs index cb8ac40a2d..44de669460 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CtrfReportTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CtrfReportTests.cs @@ -10,6 +10,7 @@ namespace MSTest.Acceptance.IntegrationTests; [TestClass] +[DoNotParallelize] public sealed class CtrfReportTests : AcceptanceTestBase { [TestMethod] @@ -33,9 +34,9 @@ public async Task CtrfReport_WhenTestsArePassingAndFailing_CtrfFileIsGeneratedWi Assert.Contains(@"""generatedBy"": ""Microsoft.Testing.Extensions.CtrfReport@", ctrfContent, ctrfContent); // Summary counts include both outcomes - Assert.Contains(@"""tests"": 2", ctrfContent, ctrfContent); + Assert.Contains(@"""tests"": 3", ctrfContent, ctrfContent); Assert.Contains(@"""passed"": 1", ctrfContent, ctrfContent); - Assert.Contains(@"""failed"": 1", ctrfContent, ctrfContent); + Assert.Contains(@"""failed"": 2", ctrfContent, ctrfContent); // Both per-test entries are present Assert.Contains(@"""name"": ""PassingTest""", ctrfContent, ctrfContent); @@ -48,17 +49,41 @@ public async Task CtrfReport_WhenTestsArePassingAndFailing_CtrfFileIsGeneratedWi Assert.Contains("Assert.AreEqual", ctrfContent, ctrfContent); using var document = JsonDocument.Parse(ctrfContent); - Assert.AreEqual("0.2.0", document.RootElement.GetProperty("specVersion").GetString()); - JsonElement[] tests = [.. document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()]; - Assert.HasCount(2, tests); + Assert.AreEqual("0.3.0", document.RootElement.GetProperty("specVersion").GetString()); + JsonElement results = document.RootElement.GetProperty("results"); + JsonElement summary = results.GetProperty("summary"); + Assert.AreEqual(3, summary.GetProperty("tests").GetInt32()); + Assert.AreEqual(1, summary.GetProperty("passed").GetInt32()); + Assert.AreEqual(2, summary.GetProperty("failed").GetInt32()); + JsonElement[] tests = [.. results.GetProperty("tests").EnumerateArray()]; + Assert.HasCount(3, tests); + Assert.AreSequenceEqual( + ["FailingTest", "MultipleComparisonFailures", "PassingTest"], + tests.Select(test => test.GetProperty("name").GetString()!).OrderBy(name => name, StringComparer.Ordinal).ToArray()); Assert.IsTrue(tests.All(test => !string.IsNullOrEmpty(test.GetProperty("testId").GetString()))); string[] executionIds = [.. tests.Select(test => test.GetProperty("executionId").GetString()!)]; Assert.IsTrue(executionIds.All(executionId => Guid.TryParse(executionId, out _))); - Assert.HasCount(2, executionIds.Distinct()); + Assert.HasCount(3, executionIds.Distinct()); string[] attemptIds = [.. tests.Select(test => test.GetProperty("attemptId").GetString()!)]; Assert.IsTrue(attemptIds.All(attemptId => Guid.TryParse(attemptId, out _))); - Assert.HasCount(2, attemptIds.Distinct()); + Assert.HasCount(3, attemptIds.Distinct()); Assert.IsEmpty(attemptIds.Intersect(executionIds, StringComparer.Ordinal)); + JsonElement passing = tests.Single(test => test.GetProperty("name").GetString() == "PassingTest"); + Assert.AreEqual("passed", passing.GetProperty("status").GetString()); + Assert.IsFalse(passing.TryGetProperty("assertionFailures", out _)); + JsonElement failing = tests.Single(test => test.GetProperty("name").GetString() == "FailingTest"); + Assert.AreEqual("failed", failing.GetProperty("status").GetString()); + Assert.IsTrue(failing.TryGetProperty("assertionFailures", out JsonElement failures), "A real Assert.AreEqual failure must retain assertionFailures."); + JsonElement comparison = Assert.ContainsSingle(failures.EnumerateArray()); + Assert.AreSequenceEqual(["expected", "actual"], comparison.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual("1", comparison.GetProperty("expected").GetString()); + Assert.AreEqual("2", comparison.GetProperty("actual").GetString()); + JsonElement multiple = tests.Single(test => test.GetProperty("name").GetString() == "MultipleComparisonFailures"); + Assert.AreEqual("failed", multiple.GetProperty("status").GetString()); + Assert.IsFalse(multiple.TryGetProperty("assertionFailures", out _), "Several failed comparisons must not be presented as one ambiguous pair."); + string message = multiple.GetProperty("message").GetString()!; + Assert.Contains("2 assertion(s) failed within the assert scope.", message); + Assert.Contains("MultipleComparisonFailures", multiple.GetProperty("trace").GetString()!); } public sealed class TestAssetFixture() : TestAssetFixtureBase() @@ -111,6 +136,16 @@ public void FailingTest() { Assert.AreEqual(1, 2); } + + [TestMethod] + public void MultipleComparisonFailures() + { + using (Assert.Scope()) + { + Assert.AreEqual(10, 11, "First comparison failure"); + Assert.AreEqual(20, 21, "Second comparison failure"); + } + } } """; } @@ -150,8 +185,24 @@ public async Task CtrfReport_WithMSTestRetryAttribute_MarksRetriedTestAsFlaky() Assert.Contains("Failing on the first attempt", ctrfContent, ctrfContent); using var document = JsonDocument.Parse(ctrfContent); + JsonElement summary = document.RootElement.GetProperty("results").GetProperty("summary"); + Assert.AreEqual(1, summary.GetProperty("tests").GetInt32()); + Assert.AreEqual(1, summary.GetProperty("passed").GetInt32()); + Assert.AreEqual(0, summary.GetProperty("failed").GetInt32()); + Assert.AreEqual(1, summary.GetProperty("flaky").GetInt32()); JsonElement test = Assert.ContainsSingle( document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + Assert.AreEqual("FlakyTest", test.GetProperty("name").GetString()); + Assert.AreEqual("passed", test.GetProperty("status").GetString()); + Assert.IsFalse(test.TryGetProperty("assertionFailures", out _)); + JsonElement prior = Assert.ContainsSingle(test.GetProperty("retryAttempts").EnumerateArray()); + Assert.AreEqual("failed", prior.GetProperty("status").GetString()); + Assert.AreEqual(1, prior.GetProperty("attempt").GetInt32()); + Assert.IsTrue(prior.TryGetProperty("assertionFailures", out JsonElement failures), "The failed retry attempt must retain assertionFailures."); + JsonElement comparison = Assert.ContainsSingle(failures.EnumerateArray()); + Assert.AreSequenceEqual(["expected", "actual"], comparison.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual("2", comparison.GetProperty("expected").GetString()); + Assert.AreEqual("1", comparison.GetProperty("actual").GetString()); Assert.IsFalse(string.IsNullOrEmpty(test.GetProperty("testId").GetString())); string executionId = test.GetProperty("executionId").GetString()!; string attemptId = test.GetProperty("retryAttempts")[0].GetProperty("attemptId").GetString()!; @@ -210,11 +261,7 @@ public class UnitTest1 [Retry(3)] public void FlakyTest() { - _attempts++; - if (_attempts <= 1) - { - Assert.Fail("Failing on the first attempt"); - } + Assert.AreEqual(2, ++_attempts, "Failing on the first attempt"); } } """; diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 16d501abf2..4da5d4427e 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -179,7 +179,7 @@ public async Task CtrfReport_UsesPlatformVersion_WhenOptedIn(bool useCentralPack using var report = JsonDocument.Parse( await File.ReadAllTextAsync(Path.Combine(resultsDirectory, "version.ctrf.json"), TestContext.CancellationToken)); Assert.AreEqual($"Microsoft.Testing.Extensions.CtrfReport@{MicrosoftTestingPlatformVersion}", report.RootElement.GetProperty("generatedBy").GetString()); - Assert.AreEqual("0.2.0", report.RootElement.GetProperty("specVersion").GetString()); + Assert.AreEqual("0.3.0", report.RootElement.GetProperty("specVersion").GetString()); } [TestMethod] diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CtrfReportTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CtrfReportTests.cs index 684446e3f3..d8e77c2bfe 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CtrfReportTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CtrfReportTests.cs @@ -192,7 +192,16 @@ public async Task Ctrf_WhenTestHostCrashes_RecoversCompletedResultsAndMarksRepor JsonElement[] tests = results.GetProperty("tests").EnumerateArray().ToArray(); Assert.HasCount(2, tests); Assert.AreEqual("PassingTest", tests[0].GetProperty("name").GetString()); + Assert.AreEqual("passed", tests[0].GetProperty("status").GetString()); + Assert.IsFalse(tests[0].TryGetProperty("assertionFailures", out _)); Assert.AreEqual("FailingTest", tests[1].GetProperty("name").GetString()); + Assert.AreEqual("failed", tests[1].GetProperty("status").GetString()); + Assert.AreEqual("Expected 1 but got 2", tests[1].GetProperty("message").GetString()); + Assert.IsTrue(tests[1].TryGetProperty("assertionFailures", out JsonElement failures), "Crash recovery must retain the failed comparison."); + JsonElement comparison = Assert.ContainsSingle(failures.EnumerateArray()); + Assert.AreSequenceEqual(["expected", "actual"], comparison.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual("1", comparison.GetProperty("expected").GetString()); + Assert.AreEqual("2", comparison.GetProperty("actual").GetString()); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -350,9 +359,11 @@ public async Task Ctrf_RetryConsolidation_PreservesDuplicateUidsAndIndependentEx } [TestMethod] - [DataRow(false)] - [DataRow(true)] - public async Task Ctrf_MergingLegacyAndCurrentReports_PreservesVersionAndAttemptIdentities(bool currentFirst) + [DataRow("0.1.0", false)] + [DataRow("0.1.0", true)] + [DataRow("0.2.0", false)] + [DataRow("0.2.0", true)] + public async Task Ctrf_MergingLegacyAndCurrentReports_PreservesVersionAndAttemptIdentities(string earlierVersion, bool currentFirst) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, TargetFrameworks.NetCurrent); string resultDirectory = Path.Combine(testHost.DirectoryName, Guid.NewGuid().ToString("N")); @@ -368,17 +379,21 @@ public async Task Ctrf_MergingLegacyAndCurrentReports_PreservesVersionAndAttempt string path = Path.Combine(resultDirectory, fileName); JsonObject report = JsonNode.Parse(File.ReadAllText(path))!.AsObject(); - Assert.AreEqual("0.2.0", (string?)report["specVersion"]); + Assert.AreEqual("0.3.0", (string?)report["specVersion"]); JsonArray tests = report["results"]!["tests"]!.AsArray(); Assert.HasCount(4, tests); expectedAttemptIds.AddRange(tests.Select(test => (string)test!["attemptId"]!)); if (index == (currentFirst ? 2 : 1)) { - report["specVersion"] = "0.1.0"; + report["specVersion"] = earlierVersion; foreach (JsonObject legacyTest in tests.Select(test => test!.AsObject())) { - legacyTest["extra"]!["mtpAttemptId"] = (string)legacyTest["attemptId"]!; - legacyTest.Remove("attemptId"); + legacyTest.Remove("assertionFailures"); + if (earlierVersion == "0.1.0") + { + legacyTest["extra"]!["mtpAttemptId"] = (string)legacyTest["attemptId"]!; + legacyTest.Remove("attemptId"); + } } File.WriteAllText(path, report.ToJsonString()); @@ -393,16 +408,108 @@ public async Task Ctrf_MergingLegacyAndCurrentReports_PreservesVersionAndAttempt mergeResult.AssertOutputContains($"MERGER_LOCATION={Path.Combine(testHost.DirectoryName, "Microsoft.Testing.Extensions.CtrfReport.dll")}"); using var merged = JsonDocument.Parse(File.ReadAllText(mergedPath)); - Assert.AreEqual("0.2.0", merged.RootElement.GetProperty("specVersion").GetString()); + Assert.AreEqual("0.3.0", merged.RootElement.GetProperty("specVersion").GetString()); JsonElement[] mergedTests = [.. merged.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()]; Assert.HasCount(8, mergedTests); - Assert.HasCount(4, mergedTests.Where(test => test.TryGetProperty("attemptId", out _))); + Assert.HasCount(earlierVersion == "0.1.0" ? 4 : 8, mergedTests.Where(test => test.TryGetProperty("attemptId", out _))); Assert.HasCount(8, expectedAttemptIds.Distinct(StringComparer.Ordinal)); Assert.AreSequenceEqual( expectedAttemptIds, mergedTests.Select(test => test.TryGetProperty("attemptId", out JsonElement attemptId) ? attemptId.GetString()! : test.GetProperty("extra").GetProperty("mtpAttemptId").GetString()!).ToArray()); + JsonElement[] currentTests = [.. mergedTests.Skip(currentFirst ? 0 : 4).Take(4)]; + JsonElement[] earlierTests = [.. mergedTests.Skip(currentFirst ? 4 : 0).Take(4)]; + Assert.ContainsOnly(test => !test.TryGetProperty("assertionFailures", out _), earlierTests); + JsonElement failure = currentTests.Single(test => test.GetProperty("name").GetString() == "FailingTest"); + Assert.IsTrue(failure.TryGetProperty("assertionFailures", out JsonElement failures), "Merging must retain the current report's comparison."); + JsonElement comparison = Assert.ContainsSingle(failures.EnumerateArray()); + Assert.AreEqual("1", comparison.GetProperty("expected").GetString()); + Assert.AreEqual("2", comparison.GetProperty("actual").GetString()); + JsonElement partialTest = currentTests.Single(test => test.GetProperty("name").GetString() == "DuplicateUidFailure"); + Assert.IsTrue(partialTest.TryGetProperty("assertionFailures", out JsonElement partialFailures), "Merging must retain the empty actual side."); + JsonElement partial = Assert.ContainsSingle(partialFailures.EnumerateArray()); + Assert.IsFalse(partial.TryGetProperty("expected", out _)); + Assert.AreEqual(string.Empty, partial.GetProperty("actual").GetString()); + } + + [TestMethod] + public async Task Ctrf_MergingReleasedVersion_PreservesRunErrorsAndAttemptThreads() + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, TargetFrameworks.NetCurrent); + string resultDirectory = Path.Join(testHost.DirectoryName, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(resultDirectory); + File.WriteAllText(Path.Join(resultDirectory, "attempt-1.ctrf.json"), """ + { + "reportFormat": "CTRF", + "specVersion": "0.3.0", + "reportId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "results": { + "tool": { "name": "ForeignProducer" }, + "summary": { "tests": 1, "passed": 0, "failed": 1, "pending": 0, "skipped": 0, "other": 0, "start": 1, "stop": 2 }, + "tests": [{ + "name": "Case", "testId": "case", "executionId": "execution", + "attemptId": "22222222-2222-4222-8222-222222222222", + "status": "failed", "duration": 1, "threadId": "first-worker", "retries": 1, + "retryAttempts": [{ + "attempt": 1, "attemptId": "11111111-1111-4111-8111-111111111111", + "status": "failed", "threadId": "nested-worker" + }] + }], + "errors": [{ "message": "setup" }, { "message": "duplicate" }] + } + } + """); + File.WriteAllText(Path.Join(resultDirectory, "attempt-2.ctrf.json"), """ + { + "reportFormat": "CTRF", + "specVersion": "0.3.0", + "reportId": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "results": { + "tool": { "name": "ForeignProducer" }, + "summary": { "tests": 1, "passed": 1, "failed": 0, "pending": 0, "skipped": 0, "other": 0, "start": 3, "stop": 4 }, + "tests": [{ + "name": "Case", "testId": "case", "executionId": "execution", + "attemptId": "33333333-3333-4333-8333-333333333333", + "status": "passed", "duration": 1, "threadId": "final-worker" + }], + "errors": [{ "message": "duplicate" }, { "trace": "cleanup", "extra": { "stage": "teardown" } }] + } + } + """); + + string mergedPath = Path.Join(resultDirectory, "merged.ctrf.json"); + TestHostResult mergeResult = await testHost.ExecuteAsync( + $"--merge-ctrf \"{resultDirectory}\" \"{mergedPath}\"", + cancellationToken: TestContext.CancellationToken); + mergeResult.AssertExitCodeIs(ExitCode.Success); + mergeResult.AssertOutputContains($"MERGER_LOCATION={Path.Join(testHost.DirectoryName, "Microsoft.Testing.Extensions.CtrfReport.dll")}"); + + using var report = JsonDocument.Parse(File.ReadAllText(mergedPath)); + Assert.AreEqual("0.3.0", report.RootElement.GetProperty("specVersion").GetString()); + JsonElement results = report.RootElement.GetProperty("results"); + Assert.AreEqual(1, results.GetProperty("summary").GetProperty("tests").GetInt32()); + Assert.AreEqual(1, results.GetProperty("summary").GetProperty("passed").GetInt32()); + JsonElement test = Assert.ContainsSingle(results.GetProperty("tests").EnumerateArray()); + Assert.AreEqual("Case", test.GetProperty("name").GetString()); + Assert.AreEqual("passed", test.GetProperty("status").GetString()); + Assert.AreEqual("final-worker", test.GetProperty("threadId").GetString()); + Assert.AreEqual("33333333-3333-4333-8333-333333333333", test.GetProperty("attemptId").GetString()); + Assert.AreEqual(2, test.GetProperty("retries").GetInt32()); + JsonElement[] history = [.. test.GetProperty("retryAttempts").EnumerateArray()]; + Assert.HasCount(2, history); + Assert.AreSequenceEqual( + ["11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"], + history.Select(attempt => attempt.GetProperty("attemptId").GetString()).ToArray()); + Assert.IsTrue(history[0].TryGetProperty("threadId", out JsonElement nestedThread), "The nested attempt must retain its thread."); + Assert.AreEqual("nested-worker", nestedThread.GetString()); + Assert.IsTrue(history[1].TryGetProperty("threadId", out JsonElement firstThread), "The earlier result must retain its thread."); + Assert.AreEqual("first-worker", firstThread.GetString()); + Assert.IsTrue(results.TryGetProperty("errors", out JsonElement errors), "Run-level errors must be retained."); + const string expectedErrors = """[{"message":"setup"},{"message":"duplicate"},{"message":"duplicate"},{"trace":"cleanup","extra":{"stage":"teardown"}}]"""; + Assert.AreEqual( + JsonNode.Parse(expectedErrors)!.ToJsonString(), + JsonNode.Parse(errors.GetRawText())!.ToJsonString()); } private static void AssertCtrfReportShape(string filePath) @@ -418,8 +525,8 @@ private static void AssertCtrfReportShape(string filePath) // The dummy framework emits four tests that exercise status, attachments, and // duplicate UIDs end to end: // - PassingTest -> status: "passed" - // - FailingTest -> status: "failed" + message + attachment - // - DuplicateUidFailure -> status: "failed" + // - FailingTest -> status: "failed" + message + comparison + attachment + // - DuplicateUidFailure -> status: "failed" + missing expected / empty actual // - DuplicateUidPass -> status: "passed" with the same UID as the prior row string actual = File.ReadAllText(filePath); using (var document = JsonDocument.Parse(actual)) @@ -442,7 +549,7 @@ private static void AssertCtrfReportShape(string filePath) const string expected = """ { "reportFormat": "CTRF", - "specVersion": "0.2.0", + "specVersion": "0.3.0", "reportId": "", "runId": "", "timestamp": "", @@ -502,6 +609,12 @@ private static void AssertCtrfReportShape(string filePath) "status": "failed", "duration": , "message": "Expected 1 but got 2", + "assertionFailures": [ + { + "expected": "1", + "actual": "2" + } + ], "attachments": [ { "name": "failure.log", @@ -524,6 +637,11 @@ private static void AssertCtrfReportShape(string filePath) "status": "failed", "duration": , "message": "Transient failure", + "assertionFailures": [ + { + "actual": "" + } + ], "extra": { "uid": "test-3" } @@ -684,8 +802,8 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) return; } - // 2) A plain failing test (no Exception object so no stack trace / exception type - // are emitted; only the explanation propagates as CTRF `message`). + // 2) A comparison without an Exception: the explanation stays at test level + // while the explicit pair supplies assertionFailures. await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage( context.Request.Session.SessionUid, new TestNode() @@ -694,6 +812,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) DisplayName = "FailingTest", Properties = new PropertyBag( new FailedTestNodeStateProperty("Expected 1 but got 2"), + new AssertionFailureProperty("1", "2"), new FileArtifactProperty(new FileInfo(attachmentPath), "failure.log", "Failure diagnostics")), })); @@ -738,7 +857,9 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) { Uid = "test-3", DisplayName = "DuplicateUidFailure", - Properties = new PropertyBag(new FailedTestNodeStateProperty("Transient failure")), + Properties = new PropertyBag( + new FailedTestNodeStateProperty("Transient failure"), + new AssertionFailureProperty(null, string.Empty)), })); await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage( context.Request.Session.SessionUid, diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index e42be5acb6..8773becbe4 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -883,6 +883,7 @@ public async Task RetryFailedTests_CtrfReports_UseLogicalRunIdentityAndRecordLin { EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, "1" }, { "METHOD1", "1" }, { "RESULTDIR", resultDirectory }, + { "CTRF_ASSERTION_FAILURE", "1" }, }; // Only an explicitly supplied logical-run id correlates modules. A module execution id must not @@ -915,7 +916,7 @@ .. Directory.GetFiles(resultDirectory, "*.ctrf.json", SearchOption.AllDirectorie foreach (string file in ctrfFiles) { using var report = System.Text.Json.JsonDocument.Parse(File.ReadAllText(file)); - Assert.AreEqual("0.2.0", report.RootElement.GetProperty("specVersion").GetString()); + Assert.AreEqual("0.3.0", report.RootElement.GetProperty("specVersion").GetString()); if (seededVariable == EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID) { Assert.IsFalse(report.RootElement.TryGetProperty("runId", out _)); @@ -977,6 +978,17 @@ .. metadata.GetProperty("inputs").EnumerateArray().Select(input => input.GetProp attemptTest.GetProperty("executionId").GetString()!, attemptTest.GetProperty("attemptId").GetString()!)); Assert.IsFalse(attemptTest.GetProperty("extra").TryGetProperty("mtpAttemptId", out _)); + if (attemptTest.GetProperty("status").GetString() == "failed") + { + Assert.IsTrue(attemptTest.TryGetProperty("assertionFailures", out System.Text.Json.JsonElement failures), "The physical failed attempt must retain its comparison."); + System.Text.Json.JsonElement comparison = Assert.ContainsSingle(failures.EnumerateArray()); + Assert.AreEqual("retry expected", comparison.GetProperty("expected").GetString()); + Assert.AreEqual("retry actual", comparison.GetProperty("actual").GetString()); + } + else + { + Assert.IsFalse(attemptTest.TryGetProperty("assertionFailures", out _)); + } } Assert.HasCount(2, physicalExecutions); @@ -990,6 +1002,7 @@ .. metadata.GetProperty("inputs").EnumerateArray().Select(input => input.GetProp results.GetProperty("tests").EnumerateArray().Select(test => test.GetProperty("executionId").GetString()).Distinct(StringComparer.Ordinal)); Assert.AreEqual("passed", flakyTest.GetProperty("status").GetString()); + Assert.IsFalse(flakyTest.TryGetProperty("assertionFailures", out _)); Assert.AreEqual(physicalExecutions[0].TestId, flakyTest.GetProperty("testId").GetString()); Assert.AreEqual( physicalExecutions.Single(execution => execution.Status == "passed").ExecutionId, @@ -998,8 +1011,13 @@ .. metadata.GetProperty("inputs").EnumerateArray().Select(input => input.GetProp physicalExecutions.Single(execution => execution.Status == "passed").AttemptId, flakyTest.GetProperty("attemptId").GetString()); Assert.AreEqual(1, flakyTest.GetProperty("retries").GetInt32()); - System.Text.Json.JsonElement retryAttempt = flakyTest.GetProperty("retryAttempts")[0]; + System.Text.Json.JsonElement retryAttempt = Assert.ContainsSingle(flakyTest.GetProperty("retryAttempts").EnumerateArray()); Assert.AreEqual("failed", retryAttempt.GetProperty("status").GetString()); + Assert.IsTrue(retryAttempt.TryGetProperty("assertionFailures", out System.Text.Json.JsonElement priorFailures), "Retry consolidation must retain the previous attempt's comparison."); + System.Text.Json.JsonElement priorComparison = Assert.ContainsSingle(priorFailures.EnumerateArray()); + Assert.AreSequenceEqual(["expected", "actual"], priorComparison.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual("retry expected", priorComparison.GetProperty("expected").GetString()); + Assert.AreEqual("retry actual", priorComparison.GetProperty("actual").GetString()); Assert.AreEqual( physicalExecutions.Single(execution => execution.Status == "failed").AttemptId, retryAttempt.GetProperty("attemptId").GetString()); @@ -1372,6 +1390,10 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) else { properties = new(new FailedTestNodeStateProperty(), testMethod1Identifier); + if (Environment.GetEnvironmentVariable("CTRF_ASSERTION_FAILURE") == "1") + { + properties.Add(new AssertionFailureProperty("retry expected", "retry actual")); + } } if (Environment.GetEnvironmentVariable("TRX_ATTACHMENTS") == "1") diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportEngineTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportEngineTests.cs index 41d52bdfcb..16b44f33ac 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportEngineTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportEngineTests.cs @@ -66,7 +66,7 @@ public async Task GenerateReportAsync_WritesValidCtrfJson_WithRequiredTopLevelFi JsonElement root = document.RootElement; Assert.AreEqual("CTRF", root.GetProperty("reportFormat").GetString()); - Assert.AreEqual("0.2.0", root.GetProperty("specVersion").GetString()); + Assert.AreEqual("0.3.0", root.GetProperty("specVersion").GetString()); Assert.IsGreaterThan(0, root.GetProperty("reportId").GetString()!.Length); Assert.IsGreaterThan(0, root.GetProperty("timestamp").GetString()!.Length); Assert.IsTrue(root.GetProperty("generatedBy").GetString()!.StartsWith("Microsoft.Testing.Extensions.CtrfReport", StringComparison.Ordinal)); @@ -132,6 +132,278 @@ public void TestResultCapture_ClassifiesTerminalOutcomes_ToCtrfStatus(string exp Assert.IsNull(result.RawStatus, "Pure CTRF outcomes should not carry rawStatus."); } + [TestMethod] + [DataRow("left", "right", DisplayName = "ExplicitComparison_BothSides")] + [DataRow("left", null, DisplayName = "ExplicitComparison_ExpectedOnly")] + [DataRow(null, "right", DisplayName = "ExplicitComparison_ActualOnly")] + [DataRow("", "right", DisplayName = "ExplicitComparison_EmptyExpected")] + [DataRow("left", "", DisplayName = "ExplicitComparison_EmptyActual")] + [DataRow("", "", DisplayName = "ExplicitComparison_BothEmpty")] + public async Task TestResultCapture_ExplicitComparison_RoundTripsOnlyKnownSides(string? expected, string? actual) + { + TestNode node = new() + { + Uid = "comparison", + DisplayName = "Comparison failure", + Properties = new( + new FailedTestNodeStateProperty("Overall failure explanation"), + new AssertionFailureProperty(expected, actual)), + }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + Assert.AreEqual("comparison", test.GetProperty("testId").GetString()); + Assert.AreEqual("Comparison failure", test.GetProperty("name").GetString()); + Assert.AreEqual("failed", test.GetProperty("status").GetString()); + Assert.AreEqual("Overall failure explanation", test.GetProperty("message").GetString()); + Assert.IsFalse(test.TryGetProperty("trace", out _)); + AssertComparison(test, expected, actual); + } + + [TestMethod] + [DataRow("explicit expected", "explicit actual", DisplayName = "ComparisonPrecedence_BothSides")] + [DataRow(null, "", DisplayName = "ComparisonPrecedence_MissingExpectedEmptyActual")] + [DataRow("", null, DisplayName = "ComparisonPrecedence_EmptyExpectedMissingActual")] + public async Task TestResultCapture_ExplicitComparison_TakesPrecedenceOverLegacyData(string? expected, string? actual) + { + var exception = new InvalidOperationException("Outer diagnostic", new ArgumentException("Inner diagnostic")); + exception.Data["assert.expected"] = "legacy expected"; + exception.Data["assert.actual"] = "legacy actual"; + TestNode node = new() + { + Uid = "precedence", + DisplayName = "Explicit comparison", + Properties = new( + new FailedTestNodeStateProperty(exception, "Overall diagnostics"), + new AssertionFailureProperty(expected, actual)), + }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + Assert.AreEqual("Overall diagnostics", test.GetProperty("message").GetString()); + Assert.AreEqual(exception.ToString(), test.GetProperty("trace").GetString()); + AssertComparison(test, expected, actual); + } + + [TestMethod] + [DataRow("legacy expected", "legacy actual", "legacy expected", "legacy actual", DisplayName = "LegacyComparison_StringPair")] + [DataRow(null, null, null, null, DisplayName = "LegacyComparison_NoDataDoesNotParseMessage")] + [DataRow("", 12, "", null, DisplayName = "LegacyComparison_EmptyExpectedNonStringActual")] + [DataRow(12, "", null, "", DisplayName = "LegacyComparison_NonStringExpectedEmptyActual")] + [DataRow(1, 2, null, null, DisplayName = "LegacyComparison_NonStringPair")] + public async Task TestResultCapture_LegacyComparison_UsesOnlyStringValues( + object? expectedData, object? actualData, string? expected, string? actual) + { + var exception = new InvalidOperationException("Expected 1 but got 2"); + if (expectedData is not null) + { + exception.Data["assert.expected"] = expectedData; + } + + if (actualData is not null) + { + exception.Data["assert.actual"] = actualData; + } + + TestNode node = new() + { + Uid = "legacy", + DisplayName = "Legacy comparison", + Properties = new(new FailedTestNodeStateProperty(exception)), + }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + Assert.AreEqual("Expected 1 but got 2", test.GetProperty("message").GetString()); + AssertComparison(test, expected, actual); + } + + [TestMethod] + [DataRow("passed")] + [DataRow("skipped")] + [DataRow("errored")] + [DataRow("timedOut")] + public async Task TestResultCapture_NonFailedStates_OmitComparisonMetadata(string stateName) + { + var exception = new InvalidOperationException("Not a comparison failure"); + exception.Data["assert.expected"] = "legacy expected"; + exception.Data["assert.actual"] = "legacy actual"; + TestNodeStateProperty state = stateName switch + { + "passed" => PassedTestNodeStateProperty.CachedInstance, + "skipped" => SkippedTestNodeStateProperty.CachedInstance, + "errored" => new ErrorTestNodeStateProperty(exception), + "timedOut" => new TimeoutTestNodeStateProperty(exception), + _ => throw new InvalidOperationException(), + }; + TestNode node = new() + { + Uid = "non-comparison", + DisplayName = stateName, + Properties = new(state, new AssertionFailureProperty("explicit expected", "explicit actual")), + }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + Assert.AreEqual(stateName is "errored" or "timedOut" ? "failed" : stateName, test.GetProperty("status").GetString()); + AssertComparison(test, null, null); + } + + [TestMethod] + public async Task TestResultCapture_ComparisonText_PreservesEscapedMultilineValues() + { + const string expected = """ + first "quoted" line + C:\expected\path café + last line + """; + const string actual = """ + actual "quoted" line + C:\actual\path 🙂 + different last line + """; + TestNode node = new() + { + Uid = "escaped", + DisplayName = "Escaped comparison", + Properties = new( + new FailedTestNodeStateProperty("Multiline comparison"), + new AssertionFailureProperty(expected + "\t\0", actual + "\t\0")), + }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + AssertComparison(test, expected + "\t\0", actual + "\t\0"); + } + + [TestMethod] + [DataRow(-1, false, false, DisplayName = "ComparisonLimit_Explicit_ExpectedBelowActualAbove")] + [DataRow(0, false, false, DisplayName = "ComparisonLimit_Explicit_At")] + [DataRow(1, false, false, DisplayName = "ComparisonLimit_Explicit_ExpectedAboveActualBelow")] + [DataRow(1, true, false, DisplayName = "ComparisonLimit_Explicit_SurrogateBoundary")] + [DataRow(-1, false, true, DisplayName = "ComparisonLimit_Legacy_ExpectedBelowActualAbove")] + [DataRow(0, false, true, DisplayName = "ComparisonLimit_Legacy_At")] + [DataRow(1, false, true, DisplayName = "ComparisonLimit_Legacy_ExpectedAboveActualBelow")] + [DataRow(1, true, true, DisplayName = "ComparisonLimit_Legacy_SurrogateBoundary")] + public async Task TestResultCapture_ComparisonLimits_PreserveBoundaryAndSurrogates(int boundaryOffset, bool crossesSurrogatePair, bool useLegacy) + { + int expectedPrefixLength = crossesSurrogatePair ? MaxMessageLength - 1 : MaxMessageLength + boundaryOffset; + int actualPrefixLength = crossesSurrogatePair ? MaxMessageLength - 1 : MaxMessageLength - boundaryOffset; + string expected = new string('e', expectedPrefixLength) + (crossesSurrogatePair ? "\U0001F642e" : string.Empty); + string actual = new string('a', actualPrefixLength) + (crossesSurrogatePair ? "\U0001F642a" : string.Empty); + var exception = new InvalidOperationException("Bounded comparison"); + exception.Data["assert.expected"] = expected; + exception.Data["assert.actual"] = actual; + var properties = new PropertyBag(new FailedTestNodeStateProperty(exception)); + if (!useLegacy) + { + properties.Add(new AssertionFailureProperty(expected, actual)); + } + + TestNode node = new() { Uid = "bounded", DisplayName = "Bounded comparison", Properties = properties }; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync([TestResultCapture.TryCapture(node)!]); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement test = Assert.ContainsSingle(document.RootElement.GetProperty("results").GetProperty("tests").EnumerateArray()); + int expectedRetainedLength = crossesSurrogatePair ? MaxMessageLength - 1 : Math.Min(expectedPrefixLength, MaxMessageLength); + int actualRetainedLength = crossesSurrogatePair ? MaxMessageLength - 1 : Math.Min(actualPrefixLength, MaxMessageLength); + string expectedSuffix = expected.Length > MaxMessageLength + ? $"\n…[truncated, original length: {expected.Length.ToString(CultureInfo.InvariantCulture)}]" + : string.Empty; + string actualSuffix = actual.Length > MaxMessageLength + ? $"\n…[truncated, original length: {actual.Length.ToString(CultureInfo.InvariantCulture)}]" + : string.Empty; + AssertComparison(test, new string('e', expectedRetainedLength) + expectedSuffix, new string('a', actualRetainedLength) + actualSuffix); + } + + [TestMethod] + [DataRow(false, DisplayName = "ComparisonRetries_FinalFailure")] + [DataRow(true, DisplayName = "ComparisonRetries_FinalPass")] + public async Task TestResultCapture_InProcessRetries_KeepComparisonsWithOwningAttempt(bool finalPass) + { + CapturedTestResult[] attempts = + [ + CaptureAttempt(1, true, new FailedTestNodeStateProperty("first diagnostic"), "first expected", "first actual"), + CaptureAttempt(2, true, new FailedTestNodeStateProperty("second diagnostic"), null, string.Empty), + CaptureAttempt( + 3, false, + finalPass ? PassedTestNodeStateProperty.CachedInstance : new FailedTestNodeStateProperty("final diagnostic"), + "final expected", "final actual"), + ]; + using var stream = new MemoryFileStream(); + + await CreateEngine(stream).GenerateReportAsync(attempts); + + using var document = JsonDocument.Parse(stream.GetUtf8Content()); + JsonElement results = document.RootElement.GetProperty("results"); + Assert.AreEqual(1, results.GetProperty("summary").GetProperty("tests").GetInt32()); + Assert.AreEqual(finalPass ? 1 : 0, results.GetProperty("summary").GetProperty("passed").GetInt32()); + Assert.AreEqual(finalPass ? 0 : 1, results.GetProperty("summary").GetProperty("failed").GetInt32()); + JsonElement final = Assert.ContainsSingle(results.GetProperty("tests").EnumerateArray()); + Assert.AreEqual("retry", final.GetProperty("testId").GetString()); + Assert.AreEqual(finalPass ? "passed" : "failed", final.GetProperty("status").GetString()); + Assert.AreEqual(2, final.GetProperty("retries").GetInt32()); + AssertComparison(final, finalPass ? null : "final expected", finalPass ? null : "final actual"); + JsonElement[] previous = [.. final.GetProperty("retryAttempts").EnumerateArray()]; + Assert.HasCount(2, previous); + Assert.AreSequenceEqual([1, 2], previous.Select(attempt => attempt.GetProperty("attempt").GetInt32()).ToArray()); + Assert.AreSequenceEqual(["first diagnostic", "second diagnostic"], previous.Select(attempt => attempt.GetProperty("message").GetString()!).ToArray()); + AssertComparison(previous[0], "first expected", "first actual"); + AssertComparison(previous[1], null, string.Empty); + if (!finalPass) + { + Assert.AreEqual("final diagnostic", final.GetProperty("message").GetString()); + } + + static CapturedTestResult CaptureAttempt(int number, bool isSuperseded, TestNodeStateProperty state, string? expected, string? actual) + => TestResultCapture.TryCapture(new TestNode + { + Uid = "retry", + DisplayName = "Comparison retry", + Properties = new(state, new RetryAttemptProperty(number, isSuperseded), new AssertionFailureProperty(expected, actual)), + })!; + } + + private static void AssertComparison(JsonElement test, string? expected, string? expectedActual) + { + if (expected is null && expectedActual is null) + { + Assert.IsFalse(test.TryGetProperty("assertionFailures", out _)); + return; + } + + Assert.IsTrue(test.TryGetProperty("assertionFailures", out JsonElement failures), "The failed comparison must retain assertionFailures."); + JsonElement failure = Assert.ContainsSingle(failures.EnumerateArray()); + string[] fields = expected is null ? ["actual"] : expectedActual is null ? ["expected"] : ["expected", "actual"]; + Assert.AreSequenceEqual(fields, failure.EnumerateObject().Select(property => property.Name).ToArray()); + if (expected is not null) + { + Assert.AreEqual(expected, failure.GetProperty("expected").GetString()); + } + + if (expectedActual is not null) + { + Assert.AreEqual(expectedActual, failure.GetProperty("actual").GetString()); + } + } + [TestMethod] public void TestResultCapture_ErrorState_MapsToFailed_With_RawStatus_Errored() { @@ -783,6 +1055,7 @@ public async Task GenerateReportAsync_RoundTripsErrorMessageAndStackTrace() JsonElement test = document.RootElement.GetProperty("results").GetProperty("tests")[0]; Assert.AreEqual("expected 1 got 2", test.GetProperty("message").GetString()); Assert.AreEqual("at MyAssembly.MyType.MyMethod()", test.GetProperty("trace").GetString()); + AssertComparison(test, null, null); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportGeneratorLifecycleTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportGeneratorLifecycleTests.cs index b5f6776461..b44156ff6d 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportGeneratorLifecycleTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportGeneratorLifecycleTests.cs @@ -249,6 +249,80 @@ await context.Generator.ConsumeAsync( context.Generator.Dispose(); } + [TestMethod] + public async Task ControllerChild_AssertionComparisonsSurviveJournalRoundTripAsync() + { + var fixture = new ReportBehaviorFixture(new() { ["report-ctrf-filename"] = ["recovered.json"] }); + GeneratorTestContext context = CreateGenerator(optionIsSet: true, isControllerChild: true, task: fixture.TaskService.Object); + var session = new TestSessionContextStub(); + try + { + await context.Generator.OnTestSessionStartingAsync(session); + await context.Generator.ConsumeAsync( + null!, + new TestNodeUpdateMessage(session.SessionUid, new TestNode + { + Uid = "full", + DisplayName = "Recovered comparison", + Properties = new( + new FailedTestNodeStateProperty("Full comparison diagnostic"), + new AssertionFailureProperty("journal expected", "journal actual")), + }), + CancellationToken.None); + await context.Generator.ConsumeAsync( + null!, + new TestNodeUpdateMessage(session.SessionUid, new TestNode + { + Uid = "empty", + DisplayName = "Recovered empty actual", + Properties = new( + new FailedTestNodeStateProperty("Partial comparison diagnostic"), + new AssertionFailureProperty(null, string.Empty)), + }), + CancellationToken.None); + await fixture.FinishAsync(context.Generator, session); + + Assert.ContainsSingle(context.PublishedArtifacts); + Assert.IsTrue(context.JournalStream.IsDisposed); + CapturedTestResult[] recovered = + [ + .. context.JournalStream.GetUtf8Content() + .Split(['\n'], StringSplitOptions.RemoveEmptyEntries) + .Select(record => CtrfReportGenerator.DeserializeJournalRecord(record)!.Result) + .OfType(), + ]; + Assert.HasCount(2, recovered); + var engine = new CtrfReportEngine(new( + fixture.FileSystem.Object, fixture.Module.Object, fixture.Environment.Object, fixture.Services.GetCommandLineOptions(), + fixture.Configuration.Object, fixture.Clock.Object, fixture.Framework.Object, ReportBehaviorFixture.Start, 0, CancellationToken.None)); + + (string path, string? warning) = await engine.GenerateReportAsync(recovered); + + Assert.IsNull(warning); + using var report = JsonDocument.Parse(fixture.WrittenFiles[path].Text); + JsonElement results = report.RootElement.GetProperty("results"); + Assert.AreEqual(2, results.GetProperty("summary").GetProperty("failed").GetInt32()); + JsonElement[] tests = [.. results.GetProperty("tests").EnumerateArray()]; + Assert.AreSequenceEqual(["full", "empty"], tests.Select(test => test.GetProperty("testId").GetString()!).ToArray()); + Assert.AreSequenceEqual( + ["Full comparison diagnostic", "Partial comparison diagnostic"], + tests.Select(test => test.GetProperty("message").GetString()!).ToArray()); + Assert.IsTrue(tests[0].TryGetProperty("assertionFailures", out JsonElement fullFailures), "The journal roundtrip must retain the full comparison."); + JsonElement full = Assert.ContainsSingle(fullFailures.EnumerateArray()); + Assert.AreSequenceEqual(["expected", "actual"], full.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual("journal expected", full.GetProperty("expected").GetString()); + Assert.AreEqual("journal actual", full.GetProperty("actual").GetString()); + Assert.IsTrue(tests[1].TryGetProperty("assertionFailures", out JsonElement partialFailures), "The journal roundtrip must retain the empty actual side."); + JsonElement partial = Assert.ContainsSingle(partialFailures.EnumerateArray()); + Assert.AreSequenceEqual(["actual"], partial.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.AreEqual(string.Empty, partial.GetProperty("actual").GetString()); + } + finally + { + context.Generator.Dispose(); + } + } + [TestMethod] public async Task ControllerChild_WhenJournalWriteFails_StillPublishesNormalArtifactAsync() { diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportMergerTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportMergerTests.cs index d181e97b2c..8d4002a3f6 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportMergerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/CtrfReportMergerTests.cs @@ -109,6 +109,125 @@ public void Merge_CompatibleSpecVersions_UsesVersion02(string legacyVersion, boo } } + [TestMethod] + [DataRow("0.0.0", false, false)] + [DataRow("0.0.0", true, false)] + [DataRow("0.0.0", false, true)] + [DataRow("0.0.0", true, true)] + [DataRow("0.0.4", false, false)] + [DataRow("0.0.4", true, false)] + [DataRow("0.0.4", false, true)] + [DataRow("0.0.4", true, true)] + [DataRow("0.1.0", false, false)] + [DataRow("0.1.0", true, false)] + [DataRow("0.1.0", false, true)] + [DataRow("0.1.0", true, true)] + [DataRow("0.2.0", false, false)] + [DataRow("0.2.0", true, false)] + [DataRow("0.2.0", false, true)] + [DataRow("0.2.0", true, true)] + public void Merge_CompatibleSpecVersions_UsesVersion03(string earlierVersion, bool currentFirst, bool collapseRetries) + { + JsonObject earlierTest = Attempt("Case", "failed", uid: "case"); + earlierTest["executionId"] = "shared-execution"; + if (earlierVersion == "0.2.0") + { + earlierTest["attemptId"] = "earlier-attempt"; + } + else + { + earlierTest["extra"]!["mtpAttemptId"] = "earlier-attempt"; + } + + JsonObject currentTest = Attempt("Case", "passed", uid: "case"); + currentTest["executionId"] = "shared-execution"; + currentTest["attemptId"] = "current-attempt"; + string earlier = BuildReport(specVersion: earlierVersion, testEntries: [earlierTest]); + string current = BuildReport(specVersion: "0.3.0", testEntries: [currentTest]); + CtrfMergeMode mode = collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge(currentFirst ? [current, earlier] : [earlier, current], mode))!; + + Assert.AreEqual("0.3.0", (string?)merged["specVersion"]); + JsonArray tests = merged["results"]!["tests"]!.AsArray(); + Assert.HasCount(collapseRetries ? 1 : 2, tests); + Assert.AreEqual(collapseRetries ? 1 : 2, (long)merged["results"]!["summary"]!["tests"]!); + if (collapseRetries) + { + JsonNode final = tests[0]!; + Assert.AreEqual(currentFirst ? "failed" : "passed", (string?)final["status"]); + Assert.AreEqual("shared-execution", (string?)final["executionId"]); + Assert.AreEqual( + currentFirst ? "earlier-attempt" : "current-attempt", + (string?)(final["attemptId"] ?? final["extra"]!["mtpAttemptId"])); + Assert.AreEqual( + currentFirst ? "current-attempt" : "earlier-attempt", + (string?)final["retryAttempts"]![0]!["attemptId"]); + } + else + { + Assert.AreSequenceEqual( + currentFirst ? ["passed", "failed"] : ["failed", "passed"], + tests.Select(test => (string)test!["status"]!).ToArray()); + Assert.AreEqual("current-attempt", (string?)tests[currentFirst ? 0 : 1]!["attemptId"]); + JsonNode earlierRow = tests[currentFirst ? 1 : 0]!; + Assert.AreEqual("earlier-attempt", (string?)(earlierRow["attemptId"] ?? earlierRow["extra"]!["mtpAttemptId"])); + } + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void Merge_Version03_PreservesRunErrorsInInputOrder(bool collapseRetries) + { + JsonObject first = JsonNode.Parse(BuildReport(specVersion: "0.3.0", testEntries: [Test("first", "passed")]))!.AsObject(); + first["results"]!["errors"] = JsonNode.Parse("""[{"message":"setup"},{"message":"duplicate"}]"""); + string legacy = BuildReport(specVersion: "0.2.0", testEntries: [Test("legacy", "passed")]); + JsonObject last = JsonNode.Parse(BuildReport(specVersion: "0.3.0", testEntries: [Test("last", "passed")]))!.AsObject(); + last["results"]!["errors"] = JsonNode.Parse("""[{"message":"duplicate"},{"trace":"cleanup","extra":{"stage":"teardown"}}]"""); + CtrfMergeMode mode = collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge([first.ToJsonString(), legacy, last.ToJsonString()], mode))!; + + Assert.AreEqual("0.3.0", (string?)merged["specVersion"]); + JsonNode results = merged["results"]!; + Assert.AreEqual(3, (long)results["summary"]!["tests"]!); + Assert.AreSequenceEqual( + ["first", "legacy", "last"], + results["tests"]!.AsArray().Select(test => (string)test!["name"]!).ToArray()); + const string expectedErrors = """[{"message":"setup"},{"message":"duplicate"},{"message":"duplicate"},{"trace":"cleanup","extra":{"stage":"teardown"}}]"""; + Assert.IsNotNull(results["errors"], "Run-level errors from the input reports must be retained."); + Assert.AreEqual(JsonNode.Parse(expectedErrors)!.ToJsonString(), results["errors"]!.ToJsonString()); + } + + [TestMethod] + [DataRow("0.3.0", """{"message":"setup"}""")] + [DataRow("0.3.0", """[{"message":"setup"},"unstructured"]""")] + [DataRow("0.2.0", """[null]""")] + public void Merge_Version03_WithMalformedRunErrors_Throws(string inputVersion, string errorsJson) + { + JsonObject invalid = JsonNode.Parse(BuildReport(specVersion: inputVersion))!.AsObject(); + invalid["results"]!["errors"] = JsonNode.Parse(errorsJson); + + ArgumentException exception = Assert.ThrowsExactly( + () => CtrfReportMerger.Merge([invalid.ToJsonString(), BuildReport(specVersion: "0.3.0")])); + + Assert.AreEqual("inputReports", exception.ParamName); + Assert.Contains("run-level errors", exception.Message); + } + + [TestMethod] + public void Merge_Version02_IgnoresUnrecognizedRunErrors() + { + JsonObject report = JsonNode.Parse(BuildReport(specVersion: "0.2.0"))!.AsObject(); + report["results"]!["errors"] = "unrecognized"; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge([report.ToJsonString()]))!; + + Assert.AreEqual("0.2.0", (string?)merged["specVersion"]); + Assert.IsNull(merged["results"]!["errors"]); + } + [TestMethod] [DataRow("0.0.0")] [DataRow("0.0.4")] @@ -128,8 +247,8 @@ public void Merge_WithoutVersion02_PreservesFirstSpecVersion(string firstVersion [DataRow("", true)] [DataRow("0.0.3", false)] [DataRow("0.0.3", true)] - [DataRow("0.3.0", false)] - [DataRow("0.3.0", true)] + [DataRow("0.4.0", false)] + [DataRow("0.4.0", true)] [DataRow("1.0.0", false)] [DataRow("1.0.0", true)] public void Merge_Version02WithUnreviewedSpecVersion_Throws(string? otherVersion, bool currentFirst) @@ -144,6 +263,38 @@ public void Merge_Version02WithUnreviewedSpecVersion_Throws(string? otherVersion Assert.Contains("0.2.0", exception.Message); } + [TestMethod] + [DataRow(null, false, false, DisplayName = "Version03_UndeclaredFirst_Concatenate")] + [DataRow(null, true, false, DisplayName = "Version03_UndeclaredLast_Concatenate")] + [DataRow(null, false, true, DisplayName = "Version03_UndeclaredFirst_Collapse")] + [DataRow(null, true, true, DisplayName = "Version03_UndeclaredLast_Collapse")] + [DataRow("", false, false, DisplayName = "Version03_EmptyFirst_Concatenate")] + [DataRow("", true, false, DisplayName = "Version03_EmptyLast_Concatenate")] + [DataRow("", false, true, DisplayName = "Version03_EmptyFirst_Collapse")] + [DataRow("", true, true, DisplayName = "Version03_EmptyLast_Collapse")] + [DataRow("0.4.0", false, false)] + [DataRow("0.4.0", true, false)] + [DataRow("0.4.0", false, true)] + [DataRow("0.4.0", true, true)] + public void Merge_Version03WithUnreviewedSpecVersion_Throws(string? otherVersion, bool currentFirst, bool collapseRetries) + { + string current = BuildReport(specVersion: "0.3.0"); + JsonObject other = JsonNode.Parse(BuildReport(specVersion: otherVersion))!.AsObject(); + if (otherVersion is null) + { + other.Remove("specVersion"); + } + + string otherReport = other.ToJsonString(); + CtrfMergeMode mode = collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate; + + ArgumentException exception = Assert.ThrowsExactly( + () => CtrfReportMerger.Merge(currentFirst ? [current, otherReport] : [otherReport, current], mode)); + + Assert.AreEqual("inputReports", exception.ParamName); + Assert.Contains("0.3.0", exception.Message); + } + [TestMethod] public void Merge_SkippedInputs_DoNotAffectSpecVersion() { @@ -157,7 +308,15 @@ public void Merge_SkippedInputs_DoNotAffectSpecVersion() } [TestMethod] - public async Task MergeToFileAsync_IncompatibleSpecVersions_PreservesInputsAndExistingOutput() + [DataRow("0.2.0", null, false)] + [DataRow("0.2.0", null, true)] + [DataRow("0.2.0", "0.4.0", false)] + [DataRow("0.2.0", "0.4.0", true)] + [DataRow("0.3.0", null, false)] + [DataRow("0.3.0", null, true)] + [DataRow("0.3.0", "0.4.0", false)] + [DataRow("0.3.0", "0.4.0", true)] + public async Task MergeToFileAsync_IncompatibleSpecVersions_PreservesInputsAndExistingOutput(string currentVersion, string? otherVersion, bool collapseRetries) { string tempDirectory = Path.Combine(Path.GetTempPath(), $"ctrf-version-merge-{Guid.NewGuid():N}"); try @@ -166,14 +325,22 @@ public async Task MergeToFileAsync_IncompatibleSpecVersions_PreservesInputsAndEx string currentPath = Path.Combine(tempDirectory, "current.json"); string unsupportedPath = Path.Combine(tempDirectory, "unsupported.json"); string outputPath = Path.Combine(tempDirectory, "merged.json"); - string current = BuildReport(specVersion: "0.2.0"); - string unsupported = BuildReport(specVersion: "0.3.0"); + string current = BuildReport(specVersion: currentVersion); + JsonObject other = JsonNode.Parse(BuildReport(specVersion: otherVersion))!.AsObject(); + if (otherVersion is null) + { + other.Remove("specVersion"); + } + + string unsupported = other.ToJsonString(); File.WriteAllText(currentPath, current); File.WriteAllText(unsupportedPath, unsupported); File.WriteAllText(outputPath, "previous output"); ArgumentException exception = await Assert.ThrowsExactlyAsync( - () => CtrfReportMerger.MergeAllToFileAsync([currentPath, unsupportedPath], outputPath, CancellationToken.None)); + () => CtrfReportMerger.MergeAllToFileAsync( + [currentPath, unsupportedPath], outputPath, + collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate, CancellationToken.None)); Assert.AreEqual("inputPaths", exception.ParamName); Assert.AreEqual(current, File.ReadAllText(currentPath)); @@ -307,6 +474,40 @@ public void Merge_FirstInputAlreadyVersion02_PreservesThePreviousReportId() Assert.AreEqual("0.2.0", (string?)merged["specVersion"]); } + [TestMethod] + [DataRow(false, "e847e177-8569-dab2-76e3-c9d3d2387bf6")] + [DataRow(true, "81f87a08-c19b-5bad-53d4-2f2eff540b63")] + public void Merge_Version03_UsesDistinctDeterministicFormatIdentity(bool collapseRetries, string previousFormatId) + { + const string input = """{"reportFormat":"CTRF","specVersion":"0.3.0","results":{"tests":[]}}"""; + CtrfMergeMode mode = collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate; + CtrfMergeMode otherMode = collapseRetries ? CtrfMergeMode.Concatenate : CtrfMergeMode.CollapseRetryAttempts; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge([input], mode))!; + JsonNode repeated = JsonNode.Parse(CtrfReportMerger.Merge([input], mode))!; + JsonNode other = JsonNode.Parse(CtrfReportMerger.Merge([input], otherMode))!; + + string reportId = (string)merged["reportId"]!; + Assert.IsTrue(Guid.TryParse(reportId, out _)); + Assert.AreNotEqual(previousFormatId, reportId, "A .3 projection must not reuse the previous unsalted format identity."); + Assert.AreEqual(reportId, (string?)repeated["reportId"]); + Assert.AreNotEqual(reportId, (string?)other["reportId"]); + Assert.AreEqual("0.3.0", (string?)merged["specVersion"]); + } + + [TestMethod] + [DataRow(false, "a126f25a-6f5c-addc-8911-6d9f155e6751")] + [DataRow(true, "275d0831-c88c-e293-786d-205761003d6b")] + public void Merge_Version03_ReleasedProjectionDoesNotReuseDraftReportId(bool collapseRetries, string draftReportId) + { + const string input = """{"reportFormat":"CTRF","specVersion":"0.3.0","results":{"tests":[],"errors":[{"message":"setup"}]}}"""; + CtrfMergeMode mode = collapseRetries ? CtrfMergeMode.CollapseRetryAttempts : CtrfMergeMode.Concatenate; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge([input], mode))!; + + Assert.AreNotEqual(draftReportId, (string?)merged["reportId"]); + } + [TestMethod] public void Merge_DerivesSummaryCountersFromTests() { @@ -1079,6 +1280,154 @@ public void Merge_CollapseRetryAttempts_FlattensInProcessRetriesOfEachAttempt() Assert.AreEqual("second-attempt", (string?)retryAttempts[1]!["attemptId"]); } + [TestMethod] + [DataRow("0.2.0", "0.2.0")] + [DataRow("0.2.0", "0.3.0")] + [DataRow("0.3.0", "0.2.0")] + [DataRow("0.3.0", "0.3.0")] + public void Merge_CollapseRetryAttempts_PreservesThreadIdsOnlyInVersion03(string firstVersion, string finalVersion) + { + bool supportsRetryThreadId = firstVersion == "0.3.0" || finalVersion == "0.3.0"; + JsonObject first = Attempt("Case", "failed", uid: "case"); + first["executionId"] = "shared-execution"; + first["attemptId"] = "first-attempt"; + first["threadId"] = "first-worker"; + var expectedIds = new List(); + var expectedWorkers = new List(); + if (firstVersion == "0.3.0") + { + first["retryAttempts"] = new JsonArray(new JsonObject + { + ["attempt"] = 1, + ["attemptId"] = "first-nested", + ["status"] = "failed", + ["threadId"] = "first-nested-worker", + }); + expectedIds.Add("first-nested"); + expectedWorkers.Add("first-nested-worker"); + } + + expectedIds.Add("first-attempt"); + expectedWorkers.Add(supportsRetryThreadId ? "first-worker" : null); + JsonObject final = Attempt("Case", "passed", uid: "case"); + final["executionId"] = "shared-execution"; + final["attemptId"] = "final-attempt"; + final["threadId"] = "final-worker"; + if (finalVersion == "0.3.0") + { + final["retryAttempts"] = new JsonArray(new JsonObject + { + ["attempt"] = 1, + ["attemptId"] = "final-nested", + ["status"] = "failed", + ["threadId"] = "final-nested-worker", + }); + expectedIds.Add("final-nested"); + expectedWorkers.Add("final-nested-worker"); + } + + string[] reports = + [ + BuildReport(specVersion: firstVersion, testEntries: [first]), + BuildReport(specVersion: finalVersion, testEntries: [final]), + ]; + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge(reports, CtrfMergeMode.CollapseRetryAttempts))!; + + Assert.AreEqual(supportsRetryThreadId ? "0.3.0" : "0.2.0", (string?)merged["specVersion"]); + JsonNode test = Assert.ContainsSingle(merged["results"]!["tests"]!.AsArray())!; + Assert.AreEqual("passed", (string?)test["status"]); + Assert.AreEqual("final-attempt", (string?)test["attemptId"]); + Assert.AreEqual("final-worker", (string?)test["threadId"]); + JsonArray history = test["retryAttempts"]!.AsArray(); + Assert.HasCount(expectedIds.Count, history); + Assert.AreSequenceEqual(expectedIds, history.Select(attempt => (string)attempt!["attemptId"]!).ToArray()); + Assert.AreSequenceEqual(expectedWorkers, history.Select(attempt => (string?)attempt!["threadId"]).ToArray()); + } + + [TestMethod] + [DataRow(false, DisplayName = "ForeignComparisons_FinalFailure")] + [DataRow(true, DisplayName = "ForeignComparisons_FinalPass")] + public void Merge_CollapseRetryAttempts_PreservesOrderedAssertionFailuresAndNestedHistory(bool finalPass) + { + const string nestedFailures = """ + [{"expected":"nested expected","actual":"nested actual"},{"actual":"","extra":{"position":2}}] + """; + const string firstFailures = """ + [{"expected":"first expected","actual":"first actual","message":"entry diagnostic","trace":"entry trace","extra":{"diff":{"line":3}}},{"message":"second assertion","extra":{"labels":["x","y"]}}] + """; + const string finalNestedFailures = """ + [{"expected":"retry nested expected"},{"actual":"retry nested actual","trace":"nested trace"}] + """; + const string finalFailures = """ + [{"expected":"final expected","actual":"final actual"},{"expected":"","actual":"","extra":{"count":2}}] + """; + JsonObject first = Attempt("Comparison", "failed", uid: "case", message: "first overall diagnostic"); + first["executionId"] = "shared-execution"; + first["attemptId"] = "first-attempt"; + first["assertionFailures"] = JsonNode.Parse(firstFailures); + first["retryAttempts"] = new JsonArray(new JsonObject + { + ["attemptId"] = "nested-attempt", + ["attempt"] = 1, + ["status"] = "failed", + ["assertionFailures"] = JsonNode.Parse(nestedFailures), + }); + JsonObject final = Attempt("Comparison", finalPass ? "passed" : "failed", uid: "case", message: finalPass ? null : "final overall diagnostic"); + final["executionId"] = "shared-execution"; + final["attemptId"] = "final-attempt"; + if (!finalPass) + { + final["assertionFailures"] = JsonNode.Parse(finalFailures); + } + + final["retryAttempts"] = new JsonArray(new JsonObject + { + ["attemptId"] = "final-nested-attempt", + ["attempt"] = 1, + ["status"] = "failed", + ["assertionFailures"] = JsonNode.Parse(finalNestedFailures), + }); + string[] reports = + [ + BuildReport(specVersion: "0.3.0", testEntries: [first]), + BuildReport(specVersion: "0.3.0", testEntries: [final]), + ]; + + JsonNode merged = JsonNode.Parse(CtrfReportMerger.Merge(reports, CtrfMergeMode.CollapseRetryAttempts))!; + + JsonNode test = Assert.ContainsSingle(merged["results"]!["tests"]!.AsArray())!; + Assert.AreEqual("case", (string?)test["extra"]!["uid"]); + Assert.AreEqual("shared-execution", (string?)test["executionId"]); + Assert.AreEqual("final-attempt", (string?)test["attemptId"]); + Assert.AreEqual(finalPass ? "passed" : "failed", (string?)test["status"]); + Assert.AreEqual(3, (long)test["retries"]!); + JsonArray history = test["retryAttempts"]!.AsArray(); + Assert.HasCount(3, history); + Assert.AreSequenceEqual([1, 2, 3], history.Select(attempt => (int)attempt!["attempt"]!).ToArray()); + Assert.AreSequenceEqual( + ["nested-attempt", "first-attempt", "final-nested-attempt"], + history.Select(attempt => (string)attempt!["attemptId"]!).ToArray()); + Assert.IsNotNull(history[0]!["assertionFailures"], "The first nested attempt must retain its assertion failures."); + Assert.IsNotNull(history[1]!["assertionFailures"], "The promoted failed test must retain its assertion failures."); + Assert.IsNotNull(history[2]!["assertionFailures"], "The final execution's nested attempt must retain its assertion failures."); + Assert.AreEqual(JsonNode.Parse(nestedFailures)!.ToJsonString(), history[0]!["assertionFailures"]!.ToJsonString()); + Assert.AreEqual(JsonNode.Parse(firstFailures)!.ToJsonString(), history[1]!["assertionFailures"]!.ToJsonString()); + Assert.AreEqual(JsonNode.Parse(finalNestedFailures)!.ToJsonString(), history[2]!["assertionFailures"]!.ToJsonString()); + Assert.AreEqual("first overall diagnostic", (string?)history[1]!["message"]); + if (finalPass) + { + Assert.IsFalse(test.AsObject().ContainsKey("assertionFailures")); + Assert.IsTrue((bool)test["flaky"]!); + } + else + { + Assert.IsNotNull(test["assertionFailures"], "The final failure must retain its own assertion failures."); + Assert.AreEqual(JsonNode.Parse(finalFailures)!.ToJsonString(), test["assertionFailures"]!.ToJsonString()); + Assert.AreEqual("final overall diagnostic", (string?)test["message"]); + Assert.IsNull(test["flaky"]); + } + } + [TestMethod] public void Merge_CollapseRetryAttempts_ProjectsAttemptsOntoRetryAttemptShape() {