Skip to content

Guard Assert.IsNotNull against Task return-value regressions - #12306

Merged
Amaury Levé (Evangelink) merged 1 commit into
mainfrom
dev/amauryleve/null-assertion-naming
Nov 10, 2026
Merged

Amaury Levé (Evangelink) merged 1 commit into
mainfrom
dev/amauryleve/null-assertion-naming

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Pull request

Summary

Add three MSTest framework unit tests that preserve statement-form Assert.IsNotNull calls inside async methods for nullable Task and Task<int>. Cover the plain, string-message, and interpolated-message overloads, including nullable-flow narrowing, pending-task state, subsequent completion, and lazy interpolation.

This catches a generic value-returning overload during the unit-test build: an existing null-check statement would otherwise start returning Task and produce CS4014. No production API or behavior changes are included.

Relates to #10918. This is regression coverage only; it does not implement or close the feature request.

Design and decision record

The rationale is the downstream compatibility regression and the suggestion to explore an alternative API.

The existing packed-consumer regression already protects C# 12 consumers. These tests add an earlier guard to the normal framework unit-test compilation without adding another fixture or a new API. They use the internal TestContainer framework and the existing AwesomeAssertions conventions. Each test owns its TaskCompletionSource; there are no sleeps, shared mutable resources, or scheduling changes. A separate feature design record is not needed for this test-only change.

Demonstration

This is a nonvisual test-only change, so screenshots/video are not applicable. The meaningful before/after observation is compilation of the same statement calls:

Current void API:                         9/9 focused tests pass per TFM.
Add generic value-returning overloads:     6 CS4014 errors at the new calls.
Remove only those temporary overloads:    9/9 focused tests pass again.

Validation and regression proof

Validation used the repository-pinned SDK 12.0.100-alpha.1.26556.115, Release configuration, and runtimes 10.0.14 / 11.0.0-rc.3.26522.148.

Source provenance: base 8bdfc29f415696738d845d56aca5d438d0a068de plus test-patch SHA-256 A46D7B34123538B065668BD72D7CF1C89F02F2B872D612FC91681B5E464B25B6. Commit 070fe43f2052c635631a2c60d7dd7df8629b0833 was verified to contain that identical tested patch. These are local results, not a claim that CI has run on the commit.

The commands below retain the executed arguments, with the machine-local artifact root replaced by $evidence:

$evidence = Join-Path (Get-Location).Path 'artifacts\TestResults\Release\IsNotNull-validation'
New-Item -ItemType Directory -Force "$evidence\unit-net10", "$evidence\unit-net11" | Out-Null

.\.dotnet\dotnet.exe build .\test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj -c Release -f net10.0 -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false "-bl:$evidence\unit-build-{}.binlog" --nologo -v:minimal

.\.dotnet\dotnet.exe test --project .\test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj -c Release -f net10.0 --no-build -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false -p:UsingDotNetTest=true "-p:ArtifactsTestResultsDir=$evidence\unit-net10" "-bl:$evidence\unit-net10\test-{}.binlog" --treenode-filter '/*/*/AssertTests/IsNotNull*' --show-test-results all

.\.dotnet\dotnet.exe test --project .\test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj -c Release -f net11.0 -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false -p:UsingDotNetTest=true "-p:ArtifactsTestResultsDir=$evidence\unit-net11" "-bl:$evidence\unit-net11\test-{}.binlog" --treenode-filter '/*/*/AssertTests/IsNotNull*' --show-test-results all
Command / selection Result
Framework unit-test build, net10.0 Exit 0; 0 warnings, 0 errors.
AssertTests.IsNotNull*, net10.0 Exit 0; 9 selected/executed/passed, 0 failed, 0 skipped.
AssertTests.IsNotNull*, net11.0 Exit 0; 9 selected/executed/passed, 0 failed, 0 skipped.
Same selection after restoring the isolated comparison to the void API Exit 0; 9 selected/executed/passed, 0 failed, 0 skipped.

TRX identities/counts and the generated JUnit XML were checked. The three added identities are:

  • IsNotNull_WhenPendingTasks_DoesNotAwaitAndLearnsNotNull
  • IsNotNull_WhenPendingTasksAndMessage_DoesNotAwaitAndLearnsNotNull
  • IsNotNull_WhenPendingTasksAndInterpolatedStringMessage_DoesNotAwaitAndLearnsNotNull

Additional package-consuming checks reused the unchanged TaskConsumerSource from AssertSourceCompatibilityTests.cs, with its existing C# 12 and warnings-as-errors settings. Focused package production succeeded with:

.\.dotnet\dotnet.exe pack .\src\TestFramework\TestFramework.Extensions\TestFramework.Extensions.csproj -c Release -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false "-bl:$evidence\framework-pack-{}.binlog" --nologo -v:minimal
.\.dotnet\dotnet.exe build .\src\Analyzers\MSTest.GlobalConfigsGenerator\MSTest.GlobalConfigsGenerator.csproj -c Release -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false "-bl:$evidence\analyzer-generator-build-{}.binlog" --nologo -v:minimal
.\.dotnet\dotnet.exe pack .\src\Analyzers\MSTest.Analyzers.Package\MSTest.Analyzers.Package.csproj -c Release --no-restore -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false "-bl:$evidence\analyzers-pack-{}.binlog" --nologo -v:minimal

All three commands exited 0. Both compared MSTest.TestFramework packages were version 5.0.0-dev, with the same aligned MSTest.Analyzers package. Separate feeds/caches were used, the effective compile/runtime assets were checked, and restored/package/runtime-copy hashes were compared.

C# 12 consumer Current package Counterfactual package
net10.0 Build exit 0; execution exit 0; expected completion, null checks, and lazy-message assertions passed. Build exit 1; six CS4014 errors; execution intentionally not attempted.
net11.0 Build exit 0; execution exit 0; expected completion, null checks, and lazy-message assertions passed. Build exit 1; six CS4014 errors; execution intentionally not attempted.

Package SHA-256 values:

  • Current framework: 0BF443AE3FFF1A3D76611A8E82E1C05C82CB57BBF5823C63E155261DE199FC41
  • Counterfactual framework: 98730AAD409C2D9D37325EDA1ABD0EF9CF7407B1D6238C0FBDD0E4B6F9A72073
  • Shared aligned analyzers: 68ADCFE7E4D302DB04B70654211A59B705A0E2D316C310351F2E448DDA6007B3

The full acceptance host was not run: the repository-wide pack bootstrap could not resolve powershell in child cmd.exe processes. The existing inner consumer was compiled/executed directly instead; this is not reported as an outer acceptance-test pass. Other unit-test targets and CI were not run locally. Detailed logs, TRX, patches, and the validation helper were retained locally rather than uploaded.

Test-value evidence

Executed: detected. In a task-owned isolated checkout, retain the exact test source and add generic IsNotNull<T> overloads returning T for the string-message and interpolated-handler forms, while keeping the original void overloads. This is an API-shape counterfactual, not a proposed implementation. API analyzers were disabled only for that comparison to permit the deliberate untracked API addition; compiler warnings remained errors.

.\.dotnet\dotnet.exe build "$comparison\test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj" -c Release -f net10.0 -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false -p:RunAnalyzers=false -p:TreatWarningsAsErrors=true "-bl:$evidence\counterfactual-unit-build-{}.binlog" --nologo -v:minimal

Result: exit 1 with exactly six CS4014 errors in AssertTests.IsNull.cs, at lines 102, 103, 122, 123, 143, and 144: one Task and one Task<int> call in each new test. This is a compilation-contract check, not six failed runtime tests or an unrelated setup failure. The independently packed C# 12 consumers also detected the same diagnostic as described above.

Remove only those temporary overloads, retaining the tests, then run:

.\.dotnet\dotnet.exe test --project "$comparison\test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj" -c Release -f net10.0 -p:SkipUapTargetFramework=true -p:EnableCodeCoverage=false -p:RunAnalyzers=false -p:TreatWarningsAsErrors=true -p:UsingDotNetTest=true "-p:ArtifactsTestResultsDir=$evidence\comparison-restored" "-bl:$evidence\comparison-restored\test-{}.binlog" --treenode-filter '/*/*/AssertTests/IsNotNull*' --show-test-results all

Result: exit 0; 9 executed/passed, 0 failed/skipped. The restored production source was verified byte-for-byte against the unchanged source in this PR, and the comparison checkout was removed after preserving the evidence.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

1 open issue
What changed in this PR

Adds regression-focused MSTest unit tests to ensure statement-form Assert.IsNotNull(...) inside async methods continues to behave as a null-check (and not accidentally become a value-returning call that would trigger CS4014) for nullable Task and Task<int>.

Changes:

  • Add three async unit tests covering Assert.IsNotNull overloads: plain, string-message, and interpolated-string-message.
  • Validate nullable-flow narrowing, pending-task state, and (for interpolated messages) lazy formatting behavior.
File Description
test/​UnitTests/​TestFramework.UnitTests/​Assertions/​AssertTests.IsNull.cs Adds three regression tests guarding Assert.IsNotNull statement-form behavior for nullable Task/Task<T> in async methods and message overloads.

Review effort: Lite

@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 10, 2026
@microsoft-github-policy-service microsoft-github-policy-service Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Nov 10, 2026
@github-actions github-actions Bot added state/approved Proposal approved; ready for implementation. and removed state/needs-review Awaiting review from the team. labels Nov 10, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Test quality review — PR #12306

Compared merge base 8bdfc29f415696738d845d56aca5d438d0a068de with head 070fe43f2052c635631a2c60d7dd7df8629b0833. Evidence applies to this head, not every intermediate commit.

Test-value evidence

Contract Test / decisive assertion Counterfactual Evidence
Statement-form Assert.IsNotNull on nullable Task/Task<int> stays void, so it does not produce CS4014 or await the task. The three IsNotNull_WhenPendingTasks* tests. Decisive checks are the compile-time statement calls plus IsCompleted.Should().BeFalse() and, for the interpolated overload, WasToStringCalled.Should().BeFalse(). Add value-returning generic IsNotNull<T> overloads. Static prediction (consistent with the PR's reported local run). The new overloads should fail the unit-test build with CS4014. I did not run it. The PR description reports an executed result of six CS4014 errors versus 9/9 passing. I could not verify that against accessible records, so treat it as an author claim.

No production code changed. The tests are regression coverage only. Runtime-only ablations (for example, asserting on null) are covered by the existing IsNotNull_PassNull_ShouldFail.

🧵 Parallel safety

PARALLEL-SAFETY RESULT
STATUS: PARTIAL

The specialist task was not launched in this run, so coverage is incomplete. This is not a clean result. My direct read of the three added methods found only method-local state (a local TaskCompletionSource and a local message tracker). I saw no static or shared mutable state, files, or timing dependence. No parallelization configuration changed (config_count=0).

Per-test assessment

Pseudo-mutation evidence below consists of static predictions, not executed mutation results.

Result Quality Test Notes How to improve
Pass B (80–89) new AssertTests.IsNotNull_WhenPendingTasks_DoesNotAwaitAndLearnsNotNull Compile-time CS4014 guard plus a pending-state check and a completion check. None
Pass B (80–89) new AssertTests.IsNotNull_WhenPendingTasksAndMessage_DoesNotAwaitAndLearnsNotNull Same guard for the string-message overload. None
Pass B (80–89) new AssertTests.IsNotNull_WhenPendingTasksAndInterpolatedStringMessage_DoesNotAwaitAndLearnsNotNull Also checks that the interpolated message is not formatted when the assertion passes. None
  • Pseudo-mutation (static): If IsNotNull awaited or blocked on the task, IsCompleted.Should().BeFalse() would likely detect it, so that is predicted as killed (inferred). Eagerly formatting the message would likely be caught by WasToStringCalled, also predicted as killed (inferred). A null-ignoring IsNotNull is not detected by these tests (candidate survivor, unverified), but IsNotNull_PassNull_ShouldFail covers that contract.
  • Inline comments: None. The one existing live thread, from Copilot, is about setup duplication. That is a rubric-only maintainability point and not a verified defect, so I did not duplicate it.
  • Limitations: The production IsNotNull bodies were not traced beyond the test contract.

<sub>This advisory review is heuristic and non-blocking.

Re-run the combined review with /review-tests, or only the parallel-safety specialist with /parallel-audit.</sub>

🤖 Automated content by GitHub Copilot. Generated by the Test Quality Review on PR (on open / sync) workflow. · copilot · auto · ~24 AIC · ⌖ ~1 AIC · ⊞ 8.1K

@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 10, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Copilot expert review — workflow run

Reviewed the single changed file (AssertTests.IsNull.cs). No blocking issues.

  • The tests use .Should(), which matches this project's AwesomeAssertions style.
  • Using async test methods to avoid CS4014 is reasonable, and the comment explains why.
  • The IsCompleted check, the completion of the TaskCompletionSource and the WasToStringCalled check are deterministic. RunContinuationsAsynchronously is a good choice.
  • The nullable-flow check is implicit: task.IsCompleted and await task after Assert.IsNotNull only compile warning-free if the [NotNull] annotation applies. Warnings are presumably errors in this repo.

Non-blocking suggestions:

  1. The three tests are near-duplicates. They could share a small helper, but explicit per-overload tests are acceptable.
  2. Nothing here proves "does not await" beyond IsCompleted == false, because IsNotNull is synchronous. That is fine for a regression guard.

Test-value evidence: Not executed (read-only review of untrusted PR code). These are static predictions only. The tests should fail to compile or warn if the Task/Task<T> overloads lose their null-state annotation, but I did not verify that against the base revision.

@microsoft-github-policy-service microsoft-github-policy-service Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Nov 10, 2026
@github-actions github-actions Bot added state/approved Proposal approved; ready for implementation. and removed state/needs-review Awaiting review from the team. state/approved Proposal approved; ready for implementation. labels Nov 10, 2026
@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 10, 2026
@github-actions github-actions Bot added state/approved Proposal approved; ready for implementation. and removed state/needs-review Awaiting review from the team. state/approved Proposal approved; ready for implementation. labels Nov 10, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 471a807 into main Nov 10, 2026
51 of 54 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/null-assertion-naming branch November 10, 2026 12:44
@github-actions github-actions Bot removed the state/approved Proposal approved; ready for implementation. label Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants