Skip to content

Use query providers for MSTest count and emptiness assertions - #12603

Merged
Amaury Levé (Evangelink) merged 1 commit into
mainfrom
dev/amauryleve/collection-predicate-assertions-aed
Nov 24, 2026
Merged

Amaury Levé (Evangelink) merged 1 commit into
mainfrom
dev/amauryleve/collection-predicate-assertions-aed

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 797c7e53a10927dd48970d8aeff5b8f4de9d71c7

Dimension Assessment Rationale
Change confidence 8.5/10 ↑ A recording provider observed scalar execution without enumeration; replacing the provider count made the targeted test fail.
↑ The packaged framework and analyzer passed all three consumer cases.
↓ Explicit-generic null/default literals can stop compiling. Ten unrelated analyzer tests failed locally because generator outputs were missing.

Pull request

Summary

Assert.HasCount, Assert.IsEmpty, and Assert.IsNotEmpty can now ask an IQueryable<T> provider for a scalar result instead of enumerating the matching items. HasCount and IsEmpty request Count; this lets IsEmpty report the actual count on failure without issuing a second query. IsNotEmpty requests Any. Interpolated failure messages stay lazy. Provider exceptions propagate rather than triggering a fallback to enumeration.

Closes #12244

Design and decision record

Decision record: native scalar assertion support. Explicit overloads preserve the caller's choice: AsEnumerable() returns the same object, so a runtime type check inside the enumerable overload would ignore that choice. MSTEST0090 follows the overload the compiler selects; its guidance for ContainsSingle is unchanged.

Source compatibility: On recompilation, explicit-generic calls such as Assert.IsEmpty<int>(default!) are ambiguous between the array and queryable overloads (CS0121). The same applies to HasCount and IsNotEmpty with an untyped null/default literal. A typed argument, e.g. (IEnumerable<int>)default!, selects the existing enumerable path. No existing signature was removed.

Demonstration

These two calls from the packaged consumer illustrate the difference. There is no UI or provider-specific SQL to show.

Assert.HasCount(2, query);                // Provider Count; no MSTEST0090.
Assert.HasCount(2, query.AsEnumerable()); // Enumerable count; MSTEST0090 still applies.

Validation and regression proof

Local Windows results with the pinned SDK 12.0.100-alpha.1.26570.125 and the source committed at the assessed revision:

Check Result
Framework unit tests All passed on net48 (1,736), net10.0 (1,892), net11.0 (1,892), and net10.0-windows (1,899).
Analyzer unit tests on net10.0 20/20 focused cases passed. Full run: 3,049 passed, 10 failed, 1 skipped. The failures expected missing MSTest.GlobalConfigsGenerator outputs, not queryable diagnostics.
Release Shipping packages PackagedQueryableAssertionsUseNativeOverloads built and ran with the expected warnings; PublicAssertCallShapes_CompileWithCSharp12 passed for both net10.0 and net11.0. Three selected, three executed, three passed, zero skipped; outer exit 0. No particular database provider or translation was tested.
Release pack and acceptance commands (each exited 0)
.\build.cmd -pack -c Release -v:quiet "/bl:artifacts\TestResults\QueryableFeature\pack-final2-73884039168040b28b81d85941c401ba\pack.binlog"
$project = 'test\IntegrationTests\MSTest.Acceptance.IntegrationTests\MSTest.Acceptance.IntegrationTests.csproj'
$results = 'artifacts\TestResults\QueryableFeature\acceptance-final2-e25e3b5adf8743f59b84750841dc0bff'
.\.dotnet\dotnet.exe build $project -c Release -v:quiet "/bl:$results\acceptance-build.binlog"
.\.dotnet\dotnet.exe test --project $project -c Release --no-build --minimum-expected-tests 3 --no-progress --output Minimal -p:UsingDotNetTest=true "-p:ArtifactsTestResultsDir=$results" --filter-uid 11f41e7f-7852-80aa-a58d-352634ea13b4 --filter-uid 1e590805-3ea6-85a5-99e8-41c04e1c164d --filter-uid 18d4e45e-17fa-8a73-a26c-a78f8321271a

The validation record identifies the two package hashes, validation artifacts, and the known source break; raw TRX and binary logs are local, not CI results.

Test-value evidence

Base 8c841a21bf80dd5b19330547ed875f47e853d2bc; head is the assessed revision above. The comparison retained the new API and the same test. Changing just Queryable.Count(collection) to Enumerable.Count(collection) produced one failed test (exit 2): the recording provider had received no Count operation. The correct implementation produced one passed test (exit 0). This mutation proves the HasCount test distinguishes the execution paths; a separate mutation was not run for IsEmpty, IsNotEmpty, or the analyzer.

$dll = 'artifacts\bin\TestFramework.UnitTests\Debug\net10.0\Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.dll'
$uid = 'Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.AssertTests.Count_IQueryable_UsesQueryableCountWithoutEnumerating'
# Comparison worktree: 1 failed, exit 2.
.\.dotnet\dotnet.exe $dll --filter-uid $uid --minimum-expected-tests 1 --report-trx --report-trx-filename queryable-count-red.trx --results-directory "$PWD\artifacts\tmp\QueryableCounterfactual" --progress off --output minimal
# Correct implementation: 1 passed, exit 0.
.\.dotnet\dotnet.exe $dll --filter-uid $uid --minimum-expected-tests 1 --report-trx --report-trx-filename queryable-count-green-corrected.trx --results-directory artifacts\TestResults\QueryableFeature\counterfactual-green --progress off --output minimal

Add IQueryable<T> overloads for HasCount, IsEmpty, and IsNotEmpty and align MSTEST0090 with the overload the compiler selects. Keep explicitly enumerable calls on the existing path.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 10:29
@github-actions github-actions Bot added the state/needs-review Awaiting review from the team. label Nov 24, 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 #12603

Compared merge base 8c841a21bf80dd5b19330547ed875f47e853d2bc with head 797c7e53a10927dd48970d8aeff5b8f4de9d71c7. Evidence applies to this head, not every intermediate commit. No inline findings were verified.

Test-value evidence

All outcomes below are static predictions unless noted. This workflow did not run tests.

Contract Test and decisive assertion Counterfactual Result
HasCount(IQueryable) calls Queryable.Count and does not enumerate Count_IQueryable_UsesQueryableCountWithoutEnumerating asserts ScalarOperations == [Count] and EnumerationCount == 0 Switch to Enumerable.Count: the scalar-operation list is empty and enumeration is 1 Predicted detected. The PR body reports one executed red-green run for this counterfactual (exit 2 without the change, exit 0 with it). That run is the author's claim and is not independently verified.
HasCount failure message reports the actual count and provider exceptions propagate Count_IQueryable_WhenCountDiffers_* asserts the full message; ..._WhenProviderCountThrows_* asserts the exception type and message Fall back to enumeration or swallow the exception: the operation and enumeration assertions fail Predicted detected
IsEmpty(IQueryable) uses Count and reports the actual count IsEmpty_IQueryable_WhenNotEmpty_* asserts the full message with actual count: 2 and [Count] Use Any, or enumerate: the operation or message assertion fails Predicted detected
IsNotEmpty(IQueryable) uses Any and reports an empty query IsNotEmpty_IQueryable_* assert [Any] and the full failure message Use Count or enumeration: the operation assertion fails Predicted detected
Interpolated handlers are lazy on success and formatted on failure The three *_InterpolatedStringHandler_IsLazyOnSuccessAndFormatsFailure tests assert WasToStringCalled Always append, or never append: the flag assertions fail Predicted detected
MSTEST0090 stays silent for native queryable overloads and still fires for AsEnumerable(), IEnumerable casts and ContainsSingle QueryableCountAndExistenceAssertions_Diagnostic and AvoidEnumerableAssertionsOnQueryableAnalyzerTests mark [|...|] spans. Inheritance_ConstrainedQueryable_UsesNativeOverloadsWithoutDiagnostic asserts no diagnostics. Remove the new early return: the non-diagnostic cases report spurious MSTEST0090 Predicted detected
The new packaged overloads compile for C# 12 consumers and the analyzer behaves the same way when packed QueryableEnumerableAndArrayCalls in AssertSourceCompatibilityTests; PackagedQueryableAssertionsUseNativeOverloads counts four MSTEST0090 warnings by assertion name Remove an overload or the analyzer change: compilation fails or the warning count changes Unverified. Both need packed NuGets, so no executed record exists in what I can access.
Docs and PublicAPI.Unshipped.txt Not executable n/a Not applicable

Evidence gaps:

  • There is no accessible paired execution record for the IsEmpty, IsNotEmpty and analyzer mutations.
  • The explicit-generic null/default source break, Assert.IsEmpty<int>(default!) → CS0121, is documented and the compatibility test is adjusted. The adjustment shows the break is intended rather than regressed, but the break is a behavior change for consumers.

🧵 Parallel safety

Status: CLEAN. No findings. Counts: Critical=0, High=0, Warning=0, Info=0.

Test assembly Scope Notes
MSTest.Acceptance.IntegrationTests AnalyzersTests (changed) The new test uses a uniquely named generated asset with its binlog inside it, and only reads the packed NuGets.
MSTest.Analyzers.UnitTests Changed tests No shared state found.
TestFramework.UnitTests AssertTests.Items.cs The fixtures are per-test local RecordingQueryable instances.

Per-test assessment

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

Result Quality Test Notes How to improve
Pass A (90–100) new AssertTests.Count_IQueryable_UsesQueryableCountWithoutEnumerating It asserts the provider operation and zero enumeration. None
Pass A (90–100) new AssertTests.Count_IQueryable_WhenCountDiffers_ReportsActualCountWithoutEnumerating It asserts the exact failure message and the provider operation. None
Pass A (90–100) new AssertTests.Count_IQueryable_WhenProviderCountThrows_PropagatesWithoutEnumerating It asserts the exception type and message and that no enumeration occurred. None
Pass B (80–89) new AssertTests.Count_IQueryable_InterpolatedStringHandler_IsLazyOnSuccessAndFormatsFailure It covers laziness and failure formatting, but the failure message is checked with wildcards. None
Pass A (90–100) new AssertTests.IsEmpty_IQueryable_UsesQueryableCountWithoutEnumerating It asserts Count and no enumeration. None
Pass A (90–100) new AssertTests.IsEmpty_IQueryable_WhenNotEmpty_ReportsActualCountWithoutEnumerating It asserts the exact message and a single Count call. None
Pass B (80–89) new AssertTests.IsEmpty_IQueryable_InterpolatedStringHandler_IsLazyOnSuccessAndFormatsFailure It covers laziness, but the failure message is checked with wildcards. None
Pass A (90–100) new AssertTests.IsNotEmpty_IQueryable_UsesQueryableAnyWithoutEnumerating It asserts Any and no enumeration. None
Pass A (90–100) new AssertTests.IsNotEmpty_IQueryable_WhenEmpty_ReportsZeroCountWithoutEnumerating It asserts the exact message and a single Any call. None
Pass B (80–89) new AssertTests.IsNotEmpty_IQueryable_InterpolatedStringHandler_IsLazyOnSuccessAndFormatsFailure It covers laziness, but the failure message is checked with wildcards. None
Pass B (80–89) new AnalyzersTests.PackagedQueryableAssertionsUseNativeOverloads It counts four warnings by assertion name; the long body is acceptable for an integration test. None
Pass A (90–100) mod AvoidEnumerableAssertionsOnQueryableAnalyzerTests.QueryableCountAndExistenceAssertions_Diagnostic The expectDiagnostic flag selects an exact diagnostic or a clean result. None
Pass B (80–89) mod AvoidEnumerableAssertionsOnQueryableAnalyzerTests (other changed methods) The marker spans separate native overloads from enumerable-forcing forms. None
Pass A (90–100) mod AnalyzerDiagnosticContinuationTests.Inheritance_ConstrainedQueryable_UsesNativeOverloadsWithoutDiagnostic It asserts empty diagnostics for a constrained IQueryable<int>. None
Uncertain — mod AssertSourceCompatibilityTests (the ArrayAndEnumerableCalls/QueryableEnumerableAndArrayCalls source in the raw string) This is compile-time test source, not a test method. Its effect depends on packed-package compilation, which I did not run. Review the executed PublicAssertCallShapes_CompileWithCSharp12 results for the packed package.

<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 (Claude Sonnet 5.5) · ~62 AIC · ⌖ ~2 AIC · ⊞ 8.4K

@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 24, 2026
@github-actions github-actions Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Nov 24, 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 24, 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 24, 2026

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.

🔵 Needs a closer look

Maintainer acceptance is needed for the documented source-compatibility break: existing explicit-generic null/default calls become ambiguous on modern assets, and the compatibility fixture now casts those arguments rather than preserving the original call shapes.

No open issues 🎉

What changed in this PR

Adds provider-aware MSTest scalar collection assertions for #12244, allowing IQueryable<T> inputs to use query-provider operations rather than enumerate results.

Changes:

  • Adds IQueryable<T> overloads using Count for HasCount/IsEmpty and Any for IsNotEmpty, preserving lazy interpolated messages.
  • Updates MSTEST0090 to recognize native overloads while retaining guidance for enumerable-bound calls and ContainsSingle.
  • Adds provider-recording tests, packaged-consumer coverage, API declarations, and design documentation.

The PR documents a source-compatibility break for explicit-generic null/default literals, which now require typed arguments to avoid overload ambiguity.

Confidence at a glance

🟡 MSTest framework and analyzer — execution evidence is author-reported

Test-value evidence: For revision 797c7e53a10927dd48970d8aeff5b8f4de9d71c7, the PR reports a failing/passing HasCount mutation check and three passing packaged-consumer cases. Raw execution artifacts were not independently inspected; separate mutation checks for the emptiness assertions and analyzer were not reported.

File Description
test/​UnitTests/​TestFramework.UnitTests/​Assertions/​AssertTests.Items.cs Tests provider execution, failures, and lazy messages.
test/​UnitTests/​MSTest.Analyzers.UnitTests/​AvoidEnumerableAssertionsOnQueryableAnalyzerTests.cs Updates native and enumerable-bound diagnostic expectations.
test/​UnitTests/​MSTest.Analyzers.UnitTests/​AnalyzerDiagnosticContinuationTests.cs Expects no diagnostics for constrained queryable calls.
test/​IntegrationTests/​MSTest.Acceptance.IntegrationTests/​AssertSourceCompatibilityTests.cs Adds C# 12 consumer calls and typed null/default arguments.
test/​IntegrationTests/​MSTest.Acceptance.IntegrationTests/​AnalyzersTests.cs Exercises packaged assertions and analyzer diagnostics together.
src/​MSTest/​TestFramework/​PublicAPI/​PublicAPI.Unshipped.txt Declares new assertion overloads and handler constructors.
src/​MSTest/​TestFramework/​Assertions/​Assert.IsNotEmpty.cs Adds query-provider Any support.
src/​MSTest/​TestFramework/​Assertions/​Assert.IsEmpty.cs Adds queryable emptiness overloads using count diagnostics.
src/​MSTest/​TestFramework/​Assertions/​Assert.HasCount.cs Adds query-provider Count support.
src/​MSTest/​TestFramework/​Assertions/​Assert.Count.InterpolatedStringHandlers.cs Captures provider counts for lazy failure messages.
src/​MSTest/​MSTest.Analyzers/​AvoidEnumerableAssertionsOnQueryableAnalyzer.cs Suppresses MSTEST0090 for native queryable overloads.
docs/​decisions/​queryable-assertion-diagnostics.md Records design choices, compatibility impact, and validation.

Review effort: Balanced

@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 24, 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 24, 2026
@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 24, 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 24, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 207bd78 into main Nov 24, 2026
57 of 58 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/collection-predicate-assertions-aed branch November 24, 2026 12:13
@github-actions github-actions Bot removed the state/approved Proposal approved; ready for implementation. label Nov 24, 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.

Add native IQueryable<T> support for MSTest scalar collection assertions

3 participants