Skip to content

Commit 797c7e5

Browse files
EvangelinkCopilot
andcommitted
Use query providers for MSTest count and emptiness assertions
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>
1 parent 8c841a2 commit 797c7e5

12 files changed

Lines changed: 734 additions & 42 deletions

File tree

‎docs/decisions/queryable-assertion-diagnostics.md‎

Lines changed: 138 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Queryable assertion diagnostics: research and decisions
1+
# Queryable assertions: research and decisions
22

33
## Problem and contract
44

@@ -361,11 +361,146 @@ The good consumer exited 0 with zero warnings/errors; the bad consumer exited 1
361361
with only the eight expected MSTEST0090 errors. No CI result is inferred from
362362
these local runs.
363363

364+
## 2026-11-23: native scalar assertion support
365+
366+
### Problem and contract
367+
368+
Issue [#12244](https://github.com/microsoft/testfx/issues/12244) asks for
369+
provider-native scalar behavior in `Assert.HasCount`, `Assert.IsEmpty`, and
370+
`Assert.IsNotEmpty`.
371+
372+
- Add overloads taking `IQueryable<T>` alongside the existing
373+
`IEnumerable<T>` overloads. Keep both message-string and interpolated-string
374+
handler call shapes.
375+
- Use `Queryable.Count` for `HasCount` and `IsEmpty`. `IsEmpty` currently
376+
reports the exact actual count on failure; using `Any` would either lose that
377+
diagnostic or require another provider execution.
378+
- Use `Queryable.Any` for `IsNotEmpty`.
379+
- Add matching `IQueryable<T>` handler constructors so interpolated messages
380+
retain lazy evaluation and use the same provider operation as the selected
381+
assertion overload.
382+
- Do not catch provider failures or fall back to `Enumerable`. A provider that
383+
cannot translate the selected scalar operation should surface its failure;
384+
enumeration could be expensive or change semantics. No database provider or
385+
SQL behavior is promised.
386+
- Make MSTEST0090 recognize that direct calls select native overloads. Keep its
387+
warning for queryables explicitly viewed as `IEnumerable<T>` (including
388+
`AsEnumerable()`), and leave `ContainsSingle` unchanged.
389+
390+
The existing public `IEnumerable<T>` signatures and their behavior remain
391+
unchanged. A statically typed `IQueryable<T>` now selects the more-specific
392+
overload; a cast or `AsEnumerable()` retains enumerable semantics. This is an
393+
intentional source-binding and runtime behavior change for direct queryable
394+
calls, and the overloads and handler constructors must be tracked in the
395+
unshipped public API baseline.
396+
397+
### Research and alternatives
398+
399+
- On 2026-11-23, read #12244 and the current assertion, interpolated-handler,
400+
analyzer, public-API, and C# 12 source-compatibility implementations at base
401+
`8c841a21bf80dd5b19330547ed875f47e853d2bc`. The framework currently targets
402+
`netstandard2.0` and supported .NET Framework/.NET TFMs; the analyzer package
403+
targets `netstandard2.0`. The package IDs are `MSTest.TestFramework` and
404+
`MSTest.Analyzers`, with repository version
405+
`5.0.0-preview.26571.1`.
406+
- `CollectionCountHelper.GetCount` currently probes `ICollection<T>`,
407+
non-generic `ICollection`, then `Enumerable.Count`; `IsNotEmptyCore` uses
408+
`ICollection<T>` or `Enumerable.Any`. LINQ's `Enumerable.Count` checks
409+
in-memory collection and iterator capabilities; it does not dispatch to
410+
`IQueryable.Provider`.
411+
- Runtime-type probing for `IQueryable` was considered and rejected. Since
412+
`AsEnumerable()` returns the same object, such a probe cannot preserve the
413+
caller's choice to bind as `IEnumerable<T>`; it would also ask providers to
414+
translate `Count` or `Any` even when their supported operation is enumeration.
415+
Explicit overloads make provider execution opt-in through the static type.
416+
- The prior design, MSTEST0090 alone, remains a valid workaround but does not
417+
provide native assertion syntax. Broad support for other assertions remains
418+
out of scope because their return values, predicates, and diagnostic
419+
contracts differ.
420+
421+
### Consumer and validation plan
422+
423+
The producer is `MSTest.TestFramework` (`MSTest.TestFramework.dll`, all package
424+
TFMs); `MSTest.Analyzers` consumes the framework API to decide whether
425+
MSTEST0090 applies. The consumer boundary is a C# 12 package consumer using
426+
the repository-pinned SDK `12.0.100-alpha.1.26570.125`. There is no process
427+
launch, handshake, cancellation protocol, external service, or result
428+
reporting boundary in this feature. The feature author owns local package,
429+
analyzer, and source-compatibility validation; release-branch servicing or
430+
backport decisions remain for maintainers before release.
431+
432+
| Requirement / risk | Automated evidence | Rendered check / gap |
433+
| --- | --- | --- |
434+
| Direct `IQueryable<T>` assertions use provider scalar execution, do not enumerate, and report correct outcomes | Provider-recording unit tests for `HasCount`, `IsEmpty`, and `IsNotEmpty`, including failure diagnostics | Nonvisual API behavior |
435+
| Message and handler paths use provider operations while preserving lazy message evaluation | Handler tests for successful and failing assertions | Nonvisual API behavior |
436+
| Framework and analyzer packages work together for C# consumers | `PackagedQueryableAssertionsUseNativeOverloads` builds and runs against both Shipping packages; it checks no warning for three direct calls and warnings for enumerable-bound calls and `ContainsSingle` | Compiler diagnostics are the affected surface; no IDE layout change |
437+
| Explicit enumerable binding remains enumerable-bound; analyzer guidance matches the selected overload | MSTEST0090 unit tests for direct queryable calls, `AsEnumerable()` / enumerable casts, and `ContainsSingle` | No IDE surface/layout change |
438+
| Existing array, enumerable, named-argument, message, handler, and queryable calls remain compilable | Packed C# 12 `AssertSourceCompatibilityTests` consumer | No rendered surface |
439+
440+
**Source-compatibility caveat:** adding these overloads makes an existing explicit-generic null/default call such as `Assert.IsEmpty<int>(default!)` ambiguous with the array overload (`CS0121`). The C# 12 consumer exposed the same ambiguity for `HasCount`, `IsEmpty`, and `IsNotEmpty`. Callers of those shapes must explicitly bind to `IEnumerable<T>`, for example `Assert.IsEmpty<int>((IEnumerable<int>)default!)`; the source-compatibility fixture now uses that cast. This is a source break for null/default-literal calls, while existing method signatures and binaries remain unchanged.
441+
442+
Parallel-safety preflight found no shared mutable test resource: TestFramework
443+
unit tests run through the sequential `TestContainer` engine; analyzer tests run
444+
at method-level parallelism but use per-test compiler inputs; the packed
445+
consumer harness creates a unique temporary directory and package cache per
446+
asset. The change does not add process/global state or change test scheduling.
447+
448+
## Validation and test-value evidence (2026-11-24)
449+
450+
Base commit: `8c841a21bf80dd5b19330547ed875f47e853d2bc`. The implementation is
451+
uncommitted; validation below applies to the source and tests in this worktree.
452+
Source-and-test diff SHA-256 (excluding this decision record):
453+
`0CD688F50B1C51F949FBAF96CF56253E290A87AFE47F5A211EE04F8064A6EE84`.
454+
455+
| Contract / test case | Counterfactual | Without behavior | Correct implementation | Evidence / gap |
456+
| --- | --- | --- | --- | --- |
457+
| `Count_IQueryable_UsesQueryableCountWithoutEnumerating` | In a detached comparison worktree, changed the `IQueryable<T>` `HasCount` helper from `Queryable.Count` to `Enumerable.Count`; mutation patch SHA-256 `F72DEB890A6E1342DBEBB9857FBADED34194C9326D0E2A0591BC30906C608C46` | Executed: 1 failed, at the assertion expecting provider operation `Count`; exit 2 | Executed: 1 passed; exit 0 | Buildable behavior-removal test; feature patch was applied to the comparison worktree before the mutation. |
458+
| Provider-backed behavior for `HasCount`, `IsEmpty`, and `IsNotEmpty`; analyzer binding and enumerable-bound cases | No separate counterfactual for this group | Unverified | Focused analyzer tests: 20 passed, 0 failed, 0 skipped on `net10.0`; prior framework TRX reports include all 10 new provider assertion tests passing | Analyzer TRX: `artifacts\TestResults\QueryableAnalyzer\queryable-analyzer-targeted.trx`; framework TRX: `artifacts\TestResults\Debug\TestFramework.UnitTests_net10.0_x64.trx`. |
459+
| Shipping package consumer and C# 12 source compatibility | Not applicable to the scalar-behavior mutation | Unverified | 3 outer acceptance cases passed, 0 failed, 0 skipped: `PackagedQueryableAssertionsUseNativeOverloads` and `PublicAssertCallShapes_CompileWithCSharp12` for `net11.0` and `net10.0`; exit 0 | Release consumer restored the current framework package into an isolated cache and the source-compatibility helper compared the cached/runtime assembly payload with the package. |
460+
461+
The final Release pack used `.\build.cmd -pack -c Release -v:quiet
462+
"/bl:artifacts\TestResults\QueryableFeature\pack-final2-73884039168040b28b81d85941c401ba\pack.binlog"`
463+
and exited 0. Package SHA-256 values were:
464+
465+
- `MSTest.TestFramework.5.0.0-dev.nupkg`: `4DBA9718D2EC92F8DC56CCEA3DFE909EAD352A833A30A65096CE39697E7D0009`
466+
- `MSTest.Analyzers.5.0.0-dev.nupkg`: `E532875C61C2DFD7F136A610489000AD345AA98943D2C60EEE3927171C663286`
467+
468+
The acceptance host build was
469+
`.\.dotnet\dotnet.exe build test\IntegrationTests\MSTest.Acceptance.IntegrationTests\MSTest.Acceptance.IntegrationTests.csproj -c Release -v:quiet "/bl:artifacts\TestResults\QueryableFeature\acceptance-final2-e25e3b5adf8743f59b84750841dc0bff\acceptance-build.binlog"`
470+
(exit 0). Independent discovery used `dotnet test --project
471+
test\IntegrationTests\MSTest.Acceptance.IntegrationTests\MSTest.Acceptance.IntegrationTests.csproj
472+
-c Release --no-build --list-tests json` with `UsingDotNetTest=true` and
473+
reporter arguments cleared (exit 0). Execution used `--minimum-expected-tests 3`
474+
and these discovered UIDs:
475+
476+
```text
477+
11f41e7f-7852-80aa-a58d-352634ea13b4
478+
1e590805-3ea6-85a5-99e8-41c04e1c164d
479+
18d4e45e-17fa-8a73-a26c-a78f8321271a
480+
```
481+
482+
The acceptance verifier reported planned=3, selected=3, executed=3, passed=3,
483+
failed=0, skipped=0, outer process exit=0. TRX:
484+
`artifacts\TestResults\QueryableFeature\acceptance-final2-e25e3b5adf8743f59b84750841dc0bff\MSTest.Acceptance.IntegrationTests_net12.0_x64.trx`.
485+
486+
The full analyzer suite was also attempted on `net10.0`: 3,049 passed, 10 failed,
487+
and 1 skipped. The failures were unrelated global-config-generator continuation
488+
tests because expected `artifacts\bin\MSTest.GlobalConfigsGenerator\Debug\net12.0`
489+
outputs were absent. The changed queryable analyzer cases were included in the
490+
focused 20/20 passing selection; the full analyzer suite is not claimed green.
491+
The first package-consumer attempt also confirmed the null/default-literal
492+
ambiguity above; a subsequent attempt exposed and corrected an invalid
493+
`IsEmpty` test input. The final package consumer run passed.
494+
495+
These are local results, not CI results. UI rendering is not applicable to this
496+
nonvisual API/analyzer change. Release-branch servicing/backport decisions
497+
remain for maintainers before release.
498+
364499
## Open questions
365500

366501
- Extending detection to queries hidden in enumerable aliases or additional
367502
client-side LINQ chains would require a separately justified analysis scope.
368503
- Content-fetching assertions and consumed `ContainsSingle` results may deserve
369504
separate guidance, but are not count/existence-only mistakes.
370-
- No downstream rollout, servicing change, or framework runtime change is
371-
required for this additive analyzer.
505+
- No downstream rollout or runtime-protocol change is included here; maintainers
506+
still need to decide release-branch servicing/backports before release.

‎src/MSTest/MSTest.Analyzers/AvoidEnumerableAssertionsOnQueryableAnalyzer.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ private static void AnalyzeInvocation(OperationAnalysisContext context, INamedTy
7979
return;
8080
}
8181

82+
if (method.Name is not "ContainsSingle"
83+
&& method.Parameters.Any(parameter => parameter.Name == "collection" && parameter.Type.DerivesFrom(queryableSymbol)))
84+
{
85+
return;
86+
}
87+
8288
IArgumentOperation? collection = invocation.Arguments.FirstOrDefault(argument => argument.Parameter?.Name == "collection");
8389
ITypeSymbol? collectionType = collection is null ? null : GetCollectionType(collection.Value, enumerableSymbol);
8490
if (collectionType is null || !collectionType.DerivesFrom(queryableSymbol) || UsesCollectionCount(collectionType, method, collectionSymbol, genericCollectionSymbol))

‎src/MSTest/TestFramework/Assertions/Assert.Count.InterpolatedStringHandlers.cs‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting;
1515
public sealed partial class Assert
1616
{
1717
/// <summary>
18-
/// Provides an interpolated string handler used by <see cref="Assert.HasCount{T}(int, IEnumerable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>
19-
/// and <see cref="Assert.IsEmpty{T}(IEnumerable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>
18+
/// Provides an interpolated string handler used by <see cref="Assert.HasCount{T}(int, IEnumerable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>,
19+
/// <see cref="Assert.HasCount{T}(int, IQueryable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>,
20+
/// <see cref="Assert.IsEmpty{T}(IEnumerable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>, and
21+
/// <see cref="Assert.IsEmpty{T}(IQueryable{T}, ref AssertCountInterpolatedStringHandler{T}, string)"/>
2022
/// that only allocates and formats the message when the assertion is failing.
2123
/// </summary>
2224
/// <typeparam name="TItem">The type of item in the collection.</typeparam>
@@ -70,6 +72,45 @@ public AssertCountInterpolatedStringHandler(int literalLength, int formattedCoun
7072
}
7173
}
7274

75+
/// <summary>
76+
/// Initializes a new instance of the <see cref="AssertCountInterpolatedStringHandler{TItem}"/> struct.
77+
/// </summary>
78+
/// <param name="literalLength">The number of constant characters in the interpolated string.</param>
79+
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
80+
/// <param name="count">The expected item count.</param>
81+
/// <param name="collection">The query being asserted; the message is only computed when the assertion fails.</param>
82+
/// <param name="shouldAppend">When this method returns, indicates whether the interpolated string should be evaluated.</param>
83+
/// <remarks>The query provider is used to calculate the count.</remarks>
84+
public AssertCountInterpolatedStringHandler(int literalLength, int formattedCount, int count, IQueryable<TItem> collection, out bool shouldAppend)
85+
{
86+
_actualCount = Queryable.Count(collection);
87+
_expectedCount = count;
88+
shouldAppend = _actualCount != _expectedCount;
89+
if (shouldAppend)
90+
{
91+
_builder = new StringBuilder(literalLength + formattedCount);
92+
}
93+
}
94+
95+
/// <summary>
96+
/// Initializes a new instance of the <see cref="AssertCountInterpolatedStringHandler{TItem}"/> struct.
97+
/// </summary>
98+
/// <param name="literalLength">The number of constant characters in the interpolated string.</param>
99+
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
100+
/// <param name="collection">The query being asserted; the message is only computed when the assertion fails.</param>
101+
/// <param name="shouldAppend">When this method returns, indicates whether the interpolated string should be evaluated.</param>
102+
/// <remarks>The query provider is used to calculate the count.</remarks>
103+
public AssertCountInterpolatedStringHandler(int literalLength, int formattedCount, IQueryable<TItem> collection, out bool shouldAppend)
104+
{
105+
_actualCount = Queryable.Count(collection);
106+
_expectedCount = 0;
107+
shouldAppend = _actualCount != _expectedCount;
108+
if (shouldAppend)
109+
{
110+
_builder = new StringBuilder(literalLength + formattedCount);
111+
}
112+
}
113+
73114
#if NETCOREAPP3_1_OR_GREATER
74115

75116
/// <summary>

‎src/MSTest/TestFramework/Assertions/Assert.HasCount.cs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,26 @@ public static void HasCount<T>(int expected, IEnumerable<T> collection, [Interpo
3434
message.ComputeAssertion(nameof(HasCount), collectionExpression);
3535
}
3636

37+
/// <summary>
38+
/// Tests whether the query has the expected count.
39+
/// </summary>
40+
/// <typeparam name="T">The type of the query items.</typeparam>
41+
/// <param name="expected">The expected count.</param>
42+
/// <param name="collection">The query.</param>
43+
/// <param name="message">The message to display when the assertion fails.</param>
44+
/// <param name="collectionExpression">
45+
/// The syntactic expression of collection as given by the compiler via caller argument expression.
46+
/// Users shouldn't pass a value for this parameter.
47+
/// </param>
48+
/// <remarks>The query provider is used to calculate the count.</remarks>
49+
#pragma warning disable IDE0060 // Remove unused parameter
50+
public static void HasCount<T>(int expected, IQueryable<T> collection, [InterpolatedStringHandlerArgument(nameof(expected), nameof(collection))] ref AssertCountInterpolatedStringHandler<T> message, [CallerArgumentExpression(nameof(collection))] string collectionExpression = "")
51+
#pragma warning restore IDE0060 // Remove unused parameter
52+
{
53+
TelemetryCollector.TrackAssertionCall("Assert.HasCount");
54+
message.ComputeAssertion(nameof(HasCount), collectionExpression);
55+
}
56+
3757
/// <summary>
3858
/// Tests whether the collection has the expected count/length.
3959
/// </summary>
@@ -48,6 +68,21 @@ public static void HasCount<T>(int expected, IEnumerable<T> collection, [Interpo
4868
public static void HasCount<T>(int expected, IEnumerable<T> collection, string? message = "", [CallerArgumentExpression(nameof(collection))] string collectionExpression = "")
4969
=> HasCount(nameof(HasCount), expected, collection, message, collectionExpression);
5070

71+
/// <summary>
72+
/// Tests whether the query has the expected count.
73+
/// </summary>
74+
/// <typeparam name="T">The type of the query items.</typeparam>
75+
/// <param name="expected">The expected count.</param>
76+
/// <param name="collection">The query.</param>
77+
/// <param name="message">The message to display when the assertion fails.</param>
78+
/// <param name="collectionExpression">
79+
/// The syntactic expression of collection as given by the compiler via caller argument expression.
80+
/// Users shouldn't pass a value for this parameter.
81+
/// </param>
82+
/// <remarks>The query provider is used to calculate the count.</remarks>
83+
public static void HasCount<T>(int expected, IQueryable<T> collection, string? message = "", [CallerArgumentExpression(nameof(collection))] string collectionExpression = "")
84+
=> HasCount(nameof(HasCount), expected, collection, message, collectionExpression);
85+
5186
/// <summary>
5287
/// Tests whether the collection has the expected count/length.
5388
/// </summary>
@@ -248,6 +283,19 @@ private static void HasCount<T>(string assertionName, int expected, IEnumerable<
248283
ReportAssertCountFailed(assertionName, expected, actualCount, message, collectionExpression);
249284
}
250285

286+
private static void HasCount<T>(string assertionName, int expected, IQueryable<T> collection, string? message, string collectionExpression)
287+
{
288+
TelemetryCollector.TrackAssertionCall(GetTrackedAssertionName(assertionName));
289+
290+
int actualCount = Queryable.Count(collection);
291+
if (actualCount == expected)
292+
{
293+
return;
294+
}
295+
296+
ReportAssertCountFailed(assertionName, expected, actualCount, message, collectionExpression);
297+
}
298+
251299
private static void HasCount(string assertionName, int expected, IEnumerable collection, string? message, string collectionExpression)
252300
{
253301
// Cast<object>() previously validated null before entering the generic helper and tracking telemetry.

0 commit comments

Comments
 (0)