Skip to content

Detect inherited fixtures/tests from a different MSTest version (MSTEST0082) - #10508

Merged
Jakub Jareš (nohwnd) merged 17 commits into
mainfrom
nohwnd-curly-guide
Aug 11, 2026
Merged

Jakub Jareš (nohwnd) merged 17 commits into
mainfrom
nohwnd-curly-guide

Conversation

@nohwnd

@nohwnd Jakub Jareš (nohwnd) commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Fixes the silent v3/v4 inheritance breakage from #10505 by detecting it at build time.

The problem

When a [TestClass] compiled against MSTest v4 inherits a [TestInitialize] / [TestMethod] / … from a base class compiled against v3, the inherited member does not run and inherited test methods are not discovered — with no build error and no discovery error. The framework assembly was renamed:

MSTest framework assembly
v3 Microsoft.VisualStudio.TestPlatform.TestFramework
v4 MSTest.TestFramework

so the attribute baked into the v3-compiled base is a different CLR type identity than the one the v4 adapter matches, and it is silently ignored.

The rule

InheritedMemberFromDifferentMSTestVersionAnalyzer (MSTEST0082, Usage, Warning). For a test class it walks the base types and warns when an inherited lifecycle or test-method attribute resolves to a framework assembly whose name differs from the one the test project compiles against. Assembly identity is matched by name, so a benign version bump of the same framework is not flagged — only the rename is.

One rule covers the six inherited attributes (TestInitialize, TestCleanup, ClassInitialize, ClassCleanup, TestMethod, DataTestMethod), with the attribute name passed as a message argument. AssemblyInitialize/AssemblyCleanup are excluded: assembly fixtures are discovered per-assembly, never inherited, so recompiling the base cannot make them run.

It only warns when recompiling the base would actually fix the problem:

  • both the framework assembly and each inherited attribute are resolved through the canonical MSTest attribute in the applied attribute's base chain, so custom [TestClass] / [TestMethod] subclasses are handled — no false positive on a custom test-class attribute, and a custom [RetryTest : TestMethodAttribute] from a v3 base is still caught;
  • the member must be one MSTest would run/discover: public, correct static-ness, valid signature (parameterless instance fixtures, TestContext-shaped class fixtures, void/Task/ValueTask returns), class fixtures only with InheritanceBehavior.BeforeEachDerivedClass, and members overridden or hidden with new in a more-derived type are suppressed.

It's a SymbolKind.NamedType action that early-outs via IsTestClass and skips same-assembly base types.

Tests

15 unit tests. Warns: inherited [TestInitialize], inherited [TestMethod], a custom [RetryTest : TestMethodAttribute] subclass, an inheritable [ClassInitialize], and the realistic graph where the old framework is reached only through the base-library metadata (not a direct reference of the test project). Silent: same-version cross-assembly base, intra-assembly inheritance, custom [TestClass] with a same-version inherited fixture, private / overridden / new-hidden / invalid-signature members, non-inheritable [ClassInitialize], [AssemblyInitialize], and a non-test-class derived type.

🤖

…Test version

Issue #10505: when a test class compiled against MSTest v4 inherits a
[TestInitialize]/[TestMethod]/... from a base compiled against v3, the inherited
member silently does not run and inherited test methods are not discovered. The
framework assembly was renamed (Microsoft.VisualStudio.TestPlatform.TestFramework
-> MSTest.TestFramework), so the attribute on the v3-compiled base is a different
type identity than the v4 adapter matches, and there is no build or discovery error.

InheritedMemberFromDifferentMSTestVersionAnalyzer walks a test class's base types
and warns when an inherited lifecycle or test-method attribute resolves to a
framework assembly whose name differs from the one the test project compiles
against. One analyzer/rule covers all eight lifecycle and test-method attributes,
parameterized by the attribute name.

Includes unit tests reproducing the mismatch (inherited [TestInitialize] and
[TestMethod] from a v3-named base assembly) plus the legitimate cases that must
stay silent (same-version cross-assembly and intra-assembly inheritance).

🤖

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings August 7, 2026 12:24

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.

Pull request overview

Adds MSTEST0082 to detect inherited MSTest fixtures or tests compiled against a differently named framework assembly.

Changes:

  • Implements cross-version inherited-member analysis.
  • Adds analyzer tests and release tracking.
  • Adds localized diagnostic resources.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs Implements MSTEST0082.
src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs Registers the rule ID.
src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md Tracks the new rule.
src/Analyzers/MSTest.Analyzers/Resources.resx Adds diagnostic text.
src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf Adds Czech localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf Adds German localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf Adds Spanish localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf Adds French localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf Adds Italian localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf Adds Japanese localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf Adds Korean localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf Adds Polish localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf Adds Portuguese localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf Adds Russian localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf Adds Turkish localization units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf Adds Simplified Chinese units.
src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf Adds Traditional Chinese units.
test/UnitTests/MSTest.Analyzers.UnitTests/InheritedMemberFromDifferentMSTestVersionAnalyzerTests.cs Tests core diagnostic scenarios.

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Additional review notes after validating the analyzer against MSTest's custom-attribute extensibility. I am submitting these as comments only—not requesting changes—so the PR is not rejected or blocked while the author is away.

- Anchor the framework assembly on the canonical TestClassAttribute in the
  applied attribute's base chain, so a custom [TestClass] subclass no longer
  produces a false positive (Evangelink).
- Match inherited custom lifecycle/test attribute subclasses by walking the
  applied attribute's base chain to the canonical MSTest attribute, so a v3-based
  [RetryTest : TestMethodAttribute] is caught too (Evangelink).
- Only report members that would actually run/be discovered after recompiling:
  public instance test methods and instance fixtures (suppressing overridden
  ones), and public static class fixtures only when the attribute specifies
  InheritanceBehavior.BeforeEachDerivedClass.
- Drop [AssemblyInitialize]/[AssemblyCleanup]: assembly fixtures are discovered
  per-assembly, never inherited, so recompiling the base cannot make them run.
- Skip same-assembly base types; mention [DataTestMethod] in the description.
- Add tests: custom [TestClass] (no diagnostic), custom [TestMethod] subclass,
  unreferenced/missing framework assembly graph, private and overridden members,
  class-fixture inheritance mode, and assembly fixture (no diagnostic).

🤖

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings August 7, 2026 13:55
@nohwnd

Copy link
Copy Markdown
Member Author

Addressed the automated review as well (3998b0c):

  • Dropped [AssemblyInitialize]/[AssemblyCleanup] — assembly fixtures are discovered per-assembly, never inherited, so recompiling the base cannot make them run.
  • [ClassInitialize]/[ClassCleanup] now warn only when the attribute specifies InheritanceBehavior.BeforeEachDerivedClass; the default None does not flow to derived classes even in the same version.
  • Filtered to the effective inherited-member set: public instance test methods and instance fixtures (overridden base lifecycle methods are suppressed), and public static class fixtures.
  • Added a test for the unresolved/missing framework graph — the framework is compiled separately and omitted from the consumer references, so the base attribute is reached as a missing type through the base library metadata.
  • The rule description now lists [DataTestMethod], and same-assembly base types are skipped.

13 tests, all green.

🤖

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:190

  • This check does not establish that the member would actually run after recompilation. It only checks accessibility/staticness, while MSTest also rejects instance fixtures with parameters or invalid return types and class fixtures without the required TestContext shape (see MethodInfoExtensions.cs:20-30,59-66); test methods with invalid return types are likewise skipped (TestMethodValidator.cs:52-73). Such members will now receive MSTEST0082 even though the prescribed recompilation cannot make them run. Please validate the complete per-kind signature before reporting.
    private static bool WouldRunOrBeDiscoveredIfSameVersion(IMethodSymbol method, MSTestMemberKind kind, AttributeData attribute, INamedTypeSymbol testClass, INamedTypeSymbol declaringBaseType)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:197

  • Checking only overrides misses members hidden with new. MSTest suppresses an inherited initialize/cleanup whenever a valid method with the same name was seen in a more-derived type (TypeCache.ClassInfo.cs:314-316,341-343), and CLR method enumeration similarly hides a same-signature base test method. MSTEST0082 therefore warns even though recompiling the base cannot restore that member. Account for hidden declarations as well as override chains.
                    && !IsOverriddenInDerivedType(method, testClass, declaringBaseType),

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:186

  • The PR description says this rule covers all eight listed attributes, including AssemblyInitialize and AssemblyCleanup, but this mapping explicitly excludes both and the new test asserts no diagnostic. Since the exclusion matches the adapter's per-assembly discovery model, update the PR description to describe the six supported inherited attributes rather than promising eight.
        // AssemblyInitialize/AssemblyCleanup are intentionally excluded: they are discovered per-assembly, not
        // inherited, so a base library's assembly fixture never runs on a derived test class even after recompilation.

test/UnitTests/MSTest.Analyzers.UnitTests/InheritedMemberFromDifferentMSTestVersionAnalyzerTests.cs:235

  • This positive case uses an invalid class-initialize signature: MSTest requires exactly one TestContext parameter (MethodInfoExtensions.cs:20-30). Even with a same-version attribute, this method would be rejected, so the test currently codifies the analyzer's false positive instead of proving the inheritance scenario. Define the legacy TestContext type and pass it here.
                    public static void BaseClassInitialize() { }

- Validate the full per-kind signature before reporting: instance fixtures must
  be parameterless and return void/Task/ValueTask; class fixtures must be static
  with a valid (optional TestContext) parameter shape and a compatible return;
  test methods must be instance with a compatible return.
- Suppress inherited members that are hidden with `new` in a more-derived type,
  not only overrides (MSTest suppresses by name).
- Fix the class-initialize positive test to use a valid signature (TestContext
  parameter) so it demonstrates a real scenario, not an already-invalid member.
- Add tests for a `new`-hidden member and an invalid-signature fixture.
- Convert GetFrameworkAssembly and HasBeforeEachDerivedClassBehavior to LINQ to
  satisfy the code-quality analyzer.

🤖

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings August 7, 2026 14:18
@nohwnd

Copy link
Copy Markdown
Member Author

Second pass (8555a7f), addressing the follow-up review:

  • Full per-kind signature validation before reporting: parameterless instance fixtures, TestContext-shaped class fixtures, void/Task/ValueTask returns, correct static-ness. A member with a mismatched attribute but an invalid signature (which would not run even after recompiling) is no longer flagged.
  • new-hidden members are now suppressed as well as overrides — MSTest suppresses an inherited member whenever a more-derived type declares one with the same name.
  • Fixed the [ClassInitialize] positive test to use a valid signature (a TestContext parameter) so it demonstrates a real scenario rather than an already-invalid member; added tests for a new-hidden member and an invalid-signature fixture.
  • GetFrameworkAssembly and HasBeforeEachDerivedClassBehavior converted to LINQ per the code-quality analyzer.
  • PR description corrected to six inherited attributes (assembly fixtures excluded).

15 tests, all green; analyzer builds clean (0 warnings).

🤖

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:244

  • Checking only the method name suppresses real diagnostics. For example, a derived BaseInitialize(int) does not suppress a valid parameterless base initializer (the adapter only records same-name lifecycle methods with valid fixture signatures), and a differently-shaped test-method overload does not hide the inherited test. This helper nevertheless returns true for either case, so the mismatched base attribute is missed. Please apply the adapter's kind-specific hiding/signature rules rather than treating every same-name method as a replacement.
            if (type.GetMembers(baseMethod.Name).Any(member => member is IMethodSymbol))
            {

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:217

  • This return-type check accepts Task<T>/ValueTask<T> because Roslyn reports their names as Task/ValueTask, and it accepts async void through ReturnsVoid. The adapter rejects all three shapes, so this rule can warn even though recompiling the base would not make the member runnable. Please use exact Task/ValueTask symbol equality and exclude async void, as FixtureUtils.HasValidTestMethodSignature/HasValidFixtureMethodSignature already do.
        => method.ReturnsVoid
            || (method.ReturnType.ContainingNamespace is { } containingNamespace
                && string.Equals(containingNamespace.ToDisplayString(), "System.Threading.Tasks", StringComparison.Ordinal)
                && (string.Equals(method.ReturnType.Name, "Task", StringComparison.Ordinal)
                    || string.Equals(method.ReturnType.Name, "ValueTask", StringComparison.Ordinal)));

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:207

  • HasClassFixtureParameterShape allows zero parameters for both class fixture kinds, but the adapter requires [ClassInitialize] to take exactly one TestContext; only [ClassCleanup] permits zero or one. A zero-argument legacy class initializer therefore receives MSTEST0082 even though recompilation cannot make it run. Please retain whether the canonical attribute is initialize or cleanup and validate each parameter shape separately.
                MSTestMemberKind.ClassFixture
                    => method.IsStatic
                        && HasClassFixtureParameterShape(method)
                        && ReturnsVoidTaskOrValueTask(method)
                        && HasBeforeEachDerivedClassBehavior(attribute),

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:181

  • The PR description says MSTEST0082 covers all eight attributes, including AssemblyInitialize and AssemblyCleanup, while this switch intentionally supports only the six inheritable class/member attributes. Please align the stated scope with the implementation, or add the intended assembly-fixture detection path if those two attributes are still required.
        // AssemblyInitialize/AssemblyCleanup are intentionally excluded: they are discovered per-assembly, not
        // inherited, so a base library's assembly fixture never runs on a derived test class even after recompilation.
        _ => MSTestMemberKind.None,

@nohwnd
Jakub Jareš (nohwnd) marked this pull request as ready for review August 7, 2026 14:50
@github-actions

This comment has been minimized.

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fresh review of the latest head. The current automated review already captures the method-hiding, return-type, and ClassInitialize parameter-shape mismatches, so I am not duplicating those inline. This additional comment covers the remaining unresolved-metadata case. Comment-only review; no rejection or request-changes state.

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fresh code + MSTest expert review (8555a7ff)

I ran two independent reviews of the complete latest diff. They converged on the same four open semantic gaps and found no additional correctness, concurrency, localization, API, or performance issues. The PR head has not changed since the previous review, so I am consolidating the result here rather than duplicating the existing inline threads.

  1. Missing legacy PE metadata can hide inherited class fixtures. HasBeforeEachDerivedClassBehavior depends on decoded AttributeData.ConstructorArguments. In the real three-PE graph (legacy framework PE → base-library PE → consumer omitting the legacy framework), Roslyn retains the missing attribute identity but cannot bind its constructor, leaving the arguments empty. An explicit BeforeEachDerivedClass class initialize/cleanup therefore escapes MSTEST0082. The current project-reference test covers only [TestInitialize] and preserves dependency symbols. Add an emitted-PE test with MetadataReference.CreateFromImage; complete support requires metadata-blob decoding, otherwise document/limit this scope. Existing thread: InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:228.

  2. Any same-name derived method suppresses a real warning. IsHiddenOrOverriddenInDerivedType treats every derived method with the same name as a replacement. The adapter is kind-specific: an invalid/private Initialize(int) does not suppress base Initialize(), different-signature test overloads remain discoverable, and class fixtures have no ordinary name-based suppression. Make hiding signature- and member-kind-aware and add C#/VB coverage for each case. Existing current-head automated finding: line 244.

  3. Invalid return types pass analyzer validation. Name-only matching accepts Task<T> and ValueTask<T>, while ReturnsVoid also accepts async void/VB Async Sub. The adapter requires exact non-generic Task/ValueTask and rejects asynchronous void. Resolve the task symbols at compilation start, compare with SymbolEqualityComparer.Default, and require !method.IsAsync for void. Existing current-head automated finding: line 217.

  4. ClassInitialize and ClassCleanup parameter rules are conflated. The shared ClassFixture branch allows zero or one TestContext, but initialize requires exactly one while cleanup permits zero or one. Preserve distinct member kinds and add a no-diagnostic test for parameterless legacy ClassInitialize. Existing current-head automated finding: line 207.

Previously reported custom [TestClass], custom TestMethodAttribute, assembly-fixture, [DataTestMethod], private/override, and PR-scope issues are fixed. CI is green, but it does not exercise the four cases above.

This is a comment-only review: no rejection or request-changes state.

Amaury's point: the project-reference "unreferenced framework" test preserves
symbol info, so it is not equivalent to a real absent PE. In the true missing-PE
case a class fixture's [ClassInitialize(InheritanceBehavior.BeforeEachDerivedClass)]
attribute cannot bind its constructor, ConstructorArguments is empty, and the
inheritance mode cannot be read — so MSTEST0082 does not flag it. Instance
fixtures and test methods carry no constructor arguments and are unaffected.

Full attribute-blob decoding is not available to an analyzer, so:
- Document the limitation on the analyzer (type remarks + HasBeforeEachDerivedClassBehavior).
- Add real emitted-PE regression tests: instance fixture is still detected with the
  legacy framework PE absent; ClassInitialize and ClassCleanup are (documented as)
  not detected in that case.
- Correct the misleading project-reference test name/comment so it no longer claims
  equivalence with missing PE metadata.

🤖

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings August 10, 2026 07:13

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (3)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:226

  • This accepts async void, Task<T>, and ValueTask<T> because it checks only ReturnsVoid or the return type's namespace/name. MSTest rejects all three (FixtureUtils.cs:74-76,140-143; TestMethodValidator.cs:55-67), so MSTEST0082 can claim that recompilation fixes a member that would remain invalid. Require non-async void and arity-zero Task/ValueTask.
        => method.ReturnsVoid
            || (method.ReturnType.ContainingNamespace is { } containingNamespace
                && string.Equals(containingNamespace.ToDisplayString(), "System.Threading.Tasks", StringComparison.Ordinal)
                && (string.Equals(method.ReturnType.Name, "Task", StringComparison.Ordinal)
                    || string.Equals(method.ReturnType.Name, "ValueTask", StringComparison.Ordinal)));

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:255

  • This name-only suppression does not match MSTest and causes false negatives. Instance fixtures are suppressed only when the derived same-name method itself has a valid fixture signature (TypeCache.ClassInfo.cs:312-317), class fixtures are accumulated independently (TypeCache.AssemblyInfo.cs:122-139), and test-method hiding is signature-based. Thus a private/static/parameterized same-name method—or any same-name class fixture—currently hides MSTEST0082 even though recompiling the base changes execution. Make this check member-kind-aware and mirror each adapter path's hiding rules.
            if (type.GetMembers(baseMethod.Name).Any(member => member is IMethodSymbol))

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:214

  • ClassInitialize and ClassCleanup cannot share this parameter check. MSTest requires ClassInitialize to take exactly one TestContext (MethodInfoExtensions.cs:20-30 and ClassInitializeShouldBeValidAnalyzer.cs:37-41), whereas only ClassCleanup may be parameterless. As written, a parameterless legacy [ClassInitialize] receives MSTEST0082 even though recompiling it would still leave an invalid fixture. Preserve the canonical initialize/cleanup kind and apply their distinct parameter rules.

This issue also appears in the following locations of the same file:

  • line 222
  • line 255
                        && HasClassFixtureParameterShape(method)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Addresses the remaining three semantic gaps from Amaury's review:

- Return types (#3): resolve Task/ValueTask at compilation start and compare by
  symbol, so Task<T>/ValueTask<T> are rejected; require non-async void.
- ClassInitialize vs ClassCleanup params (#4): split the class-fixture kind so
  ClassInitialize requires exactly one TestContext while ClassCleanup allows zero
  or one; a parameterless legacy [ClassInitialize] is no longer flagged.
- Hiding (#2): make suppression member-kind-aware and signature-based. Instance
  fixtures are suppressed only by a same-name derived method that is itself a valid
  fixture; test methods only by a same-signature method; class fixtures accumulate
  and are never name-suppressed. Overrides still always suppress.

Adds C# tests for each case plus two Visual Basic tests confirming language parity.

🤖

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings August 10, 2026 07:39
@github-actions

This comment has been minimized.

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:347

  • GetRuntimeMethods delegates to Type.GetMethods(Everything) (ReflectionOperations.cs:68-69), which removes a base method hidden by a same-signature derived declaration before TestMethodValidator examines attributes. Requiring the derived method itself to be discoverable therefore produces a false MSTEST0082 for cases such as public new void Run() without [TestMethod]: the legacy base Run is absent both before and after recompilation. Treat any same-signature derived method as hiding the base method, and update the corresponding WhenInheritedTestMethodShadowedByNonTestMethod_Diagnostic expectation.
                    case MSTestMemberKind.TestMethod
                        when IsDiscoverableTestMethod(derivedMethod, referenceAssembly, canDiscoverInternals, taskSymbol, valueTaskSymbol)
                            && HaveSameSignature(derivedMethod, baseMethod):

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code looks good to go at head 824705c9; no major correctness, API, or test-coverage concerns found.

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fresh code and MSTest-expert review of head 824705c9, reconciled with direct reflection probes. The previous visibility/signature blockers were addressed, but two narrow false negatives remain. This is a comment-only review; no rejection or request-changes state.

…STEST0082

Two correctness gaps in the hiding/override logic, both confirmed against the
adapter source and by reflection probes:

- Generic hiding key: MSTest de-duplicates by MethodInfo.ToString(), which prints
  the method type parameter by NAME (e.g. "Void Run[T](T)"), not by ordinal. So
  Run<U>(U) and Run<T>(T) have different discovery keys and do NOT hide each other,
  while Run<T>(T) hides Run<T>(T). Compare method type parameters by name instead
  of ordinal. Flip the renamed-type-parameter test to expect a diagnostic and add a
  same-name companion that stays clean.

- Override with inheritable custom attribute: an override normally replaces the
  inherited member because standard attributes use Inherited=false. But a custom
  attribute with Inherited=true flows onto the override (the adapter reads
  attributes with inherit:true), so when it derives from a different-version
  framework type the override is discoverable only after recompiling the base - a
  real migration break. Account for the applied attribute's effective
  AttributeUsage.Inherited: keep suppressing non-inherited attributes and overrides
  that carry their own current-version attribute; report when the inheritable
  legacy attribute is the only thing that would make the override discoverable.
  Added C# and VB tests for Inherited=true, Inherited=false, and a
  current-attributed override, and made the existing override test's attribute
  Inherited=false to match the real framework.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: fa3c2d45-4786-429c-8388-e3cec14952ea
Copilot AI review requested due to automatic review settings August 10, 2026 20:22

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:394

  • Defaulting to true when AttributeUsage cannot be resolved causes a false positive for the emitted-missing-framework case. For example, a legacy standard [TestMethod] on a virtual base method plus an attribute-less override reaches this fallback; the real standard attribute has Inherited=false, so recompiling the base still leaves the override undiscoverable, but this code reports MSTEST0082. Preserve the known Inherited=false semantics for unresolved standard TestMethod, TestInitialize, and TestCleanup attributes, while retaining the default for genuinely custom attributes.
        return true;

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:92

  • This early-out does not cover every class that the adapter rejects, so the analyzer can warn even though recompiling the base cannot make any inherited member run. In particular, TypeValidator rejects a concrete test class nested in a generic container and a class with an invalid declared TestContext getter; the existing runnable-class check in DependsOnShouldBeValidAnalyzer handles both cases. Please reuse equivalent test-class validation here before reporting MSTEST0082.
        if (!classSymbol.IsTestClass(testClassAttributeSymbol)
            || classSymbol.IsAbstract
            || classSymbol.IsGenericType
            || !IsDiscoverableTestClassVisibility(classSymbol, canDiscoverInternals))

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

…ST0082)

Two further false-positive fixes:

- When the legacy framework PE is absent, the applied attribute type is unresolved
  metadata whose AttributeUsage cannot be read. IsAppliedAttributeInheritable then
  hit its fallback and defaulted to inheritable=true, which reported an
  attribute-less override of a standard (Inherited=false) fixture even though it is
  not discoverable. Since this path only runs for attributes deriving from a
  canonical MSTest attribute (all Inherited=false), the correct and conservative
  fallback is false. Added an emitted-missing-PE override regression test.

- A concrete test class nested in a generic container cannot be constructed without
  the container's type arguments, so the adapter never discovers it, but the guard
  only rejected classes with their own type parameters. Also skip classes nested in
  a generic type. Added a nested-in-generic regression test.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: fa3c2d45-4786-429c-8388-e3cec14952ea
Copilot AI review requested due to automatic review settings August 10, 2026 20:37
Address CodeQL "missed opportunity to use Where": filter usage.NamedArguments with
.Where(Key == "Inherited") instead of testing the key inside the loop. Behavior is
unchanged.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: fa3c2d45-4786-429c-8388-e3cec14952ea

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (3)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:252

  • This excludes generic methods whose type arguments cannot be inferred, but the adapter deliberately discovers generic method definitions and reports inference failures as failed tests (TestMethodValidatorTests.IsValidTestMethodShouldReturnTrueForGenericTestMethodDefinitions and GenericTestMethodTests, lines 26-27). For a legacy inherited Run<T>(), recompiling the base therefore changes it from silently absent to a discovered failing test, so this rule should warn rather than preserve the silence. Remove this inferability filter here and in IsDiscoverableTestMethod, and update the corresponding NoDiagnostic test.
                MSTestMemberKind.TestMethod
                    => !method.IsStatic
                        && ReturnsVoidTaskOrValueTask(method, taskSymbol, valueTaskSymbol)
                        && (!method.IsGenericMethod || AllGenericTypeParametersAreInferable(method)),

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:350

  • continue can let a less-derived override suppress a real mismatch. For example, if an intermediate override has its own current [TestMethod] but the final test class overrides it without an attribute, reflection surfaces the final override; the intermediate attribute is non-inheritable, while an inheritable legacy custom attribute from the original base still flows to the final override. Continuing to the intermediate method then returns true and misses the warning. Once the most-derived override is known to inherit the mismatched attribute and has no own current attribute, it is the effective method and this should return false immediately.
                    if (IsAppliedAttributeInheritable(attribute)
                        && !HasOwnCurrentVersionAttributeOfKind(derivedMethod, kind, referenceAssembly))
                    {
                        continue;

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:94

  • This discoverability guard omits TypeValidator.HasCorrectTestContextSignature. A public concrete [TestClass] that declares a TestContext-typed property with a private/abstract/static getter is rejected before method discovery, but this analyzer still reports inherited-version warnings even though recompiling the base cannot make those members run or be discovered. Resolve the current TestContext symbol and mirror the existing check in DependsOnShouldBeValidAnalyzer.HasCorrectTestContextSignature.

This issue also appears in the following locations of the same file:

  • line 249
  • line 347
        if (!classSymbol.IsTestClass(testClassAttributeSymbol)
            || classSymbol.IsAbstract
            || classSymbol.IsGenericType
            || IsNestedInGenericType(classSymbol)
            || !IsDiscoverableTestClassVisibility(classSymbol, canDiscoverInternals))

Copilot AI review requested due to automatic review settings August 10, 2026 20:44
@github-actions

This comment has been minimized.

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:143

  • This treats any assembly that defines a type with an MSTest namespace and canonical attribute name as a different MSTest version. For example, a compatibility library defining Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute in Contoso.Helpers would trigger MSTEST0082, although recompiling it against the current MSTest version cannot fix that non-MSTest attribute. Restrict the mismatch to the two known framework assembly names before reporting.
                    IAssemblySymbol? attributeAssembly = canonicalAttribute.ContainingAssembly;
                    if (attributeAssembly is null
                        || string.Equals(attributeAssembly.Name, referenceAssembly.Name, StringComparison.Ordinal))
                    {
                        continue;

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:69

  • This global metadata-name lookup disables the rule when both v3 and v4 framework assemblies are referenced. WellKnownTypeProvider deliberately returns null when multiple visible references define the same metadata name (RoslynAnalyzerHelpers/WellKnownTypeProvider.cs:143-146), so an aliased legacy reference that keeps the base attribute resolvable makes this action never register. Resolve the current framework from each source class's applied TestClass attribute (and validate its assembly) instead, so the resolved two-framework scenario is analyzed.

This issue also appears on line 139 of the same file.

            if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestClassAttribute, out INamedTypeSymbol? testClassAttributeSymbol))

The override branch used `continue` after finding the most-derived override,
letting the loop examine a less-derived override. If an intermediate override
carried its own current-version [TestMethod] (non-inheritable) while the final
override inherited an inheritable legacy custom attribute, the intermediate wrongly
suppressed the warning. Reflection only surfaces the most-derived override, which
the top-down walk finds first, so its outcome is decisive: return immediately
(report when it inherits the mismatch with no own current attribute, suppress
otherwise). Added a three-level override-chain regression test.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: fa3c2d45-4786-429c-8388-e3cec14952ea
Copilot AI review requested due to automatic review settings August 10, 2026 20:53

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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:370

  • GetRuntimeMethods calls Type.GetMethods before TestMethodValidator filters attributes, so a derived method with the same CLR signature hides the base method even when the derived method is not itself a test. Requiring IsDiscoverableTestMethod here therefore reports a false migration warning for the public new void Run() case covered below: recompiling the base still cannot make that hidden test discoverable. Treat any runtime-signature-equivalent derived method as hiding the base method and update that test expectation.
                    case MSTestMemberKind.TestMethod
                        when IsDiscoverableTestMethod(derivedMethod, referenceAssembly, canDiscoverInternals, taskSymbol, valueTaskSymbol)
                            && HaveSameSignature(derivedMethod, baseMethod):

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:494

  • CLR method signatures identify method type parameters by ordinal, not by their metadata names. Consequently Run<T>(T) and Run<U>(U) have the same runtime signature and the derived method hides the base method before MSTest de-duplication; comparing Name makes the analyzer incorrectly warn for the renamed-type-parameter test. Compare Ordinal (along with TypeParameterKind) instead.
        if (left is ITypeParameterSymbol leftTypeParameter && right is ITypeParameterSymbol rightTypeParameter)
        {
            return leftTypeParameter.TypeParameterKind == rightTypeParameter.TypeParameterKind
                && string.Equals(leftTypeParameter.Name, rightTypeParameter.Name, StringComparison.Ordinal);

src/Analyzers/MSTest.Analyzers/Resources.resx:1245

  • This remediation is incorrect when the applied custom attribute is defined in a separate library. For example, if RetryTestAttribute : TestMethodAttribute is compiled against v3 in CustomAttributes.dll and then applied in BaseLibrary.dll, rebuilding the assembly that declares TestBase leaves RetryTestAttribute based on the v3 type and does not fix discovery. The diagnostic needs to identify/recommend rebuilding the applied attribute's defining assembly for custom attributes (while retaining the base-assembly advice for canonical attributes).
    <value>The inherited member '{1}.{0}' is annotated with a '[{2}]' attribute that resolves to a canonical MSTest attribute in '{3}', a different MSTest framework assembly than this test project uses; MSTest matches these attributes by exact type identity, so the inherited '[{2}]' is silently ignored at run time. Recompile the assembly that declares '{1}' against the same MSTest version as the test project.</value>

src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:215

  • Namespace and type name alone do not establish that this is an MSTest framework attribute. A referenced library can define Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute in an unrelated assembly; this code labels it canonical and warns even though recompiling the base against the current package would not change that attribute. Also validate the canonical type's containing assembly against the recognized MSTest framework assembly names (while preserving the missing-metadata case).
            if (type.ContainingNamespace is { } containingNamespace
                && string.Equals(containingNamespace.ToDisplayString(), MSTestNamespace, StringComparison.Ordinal)
                && IsCanonicalAttributeName(type.Name))
            {

@github-actions

Copy link
Copy Markdown
Contributor

🧵 Parallel-safety audit — PR #10508

Nothing audited here touches process-global state, shared filesystem paths, or [ResourceLock] / [DoNotParallelize] declarations. Nothing to flag for parallel-safety.

The only changed test file is test/UnitTests/MSTest.Analyzers.UnitTests/InheritedMemberFromDifferentMSTestVersionAnalyzerTests.cs, adding coverage for the new InheritedMemberFromDifferentMSTestVersionAnalyzer. All added test methods are pure Roslyn VerifyCS/VerifyVB source-verification tests (in-memory compilations/diagnostics only) — no Environment.*, Directory.*/File.* mutation, CultureInfo/Thread culture writes, Console.Set*, or shared/relative filesystem paths. The one static readonly field (FrameworkReferences) is initialized once and only ever read afterward — no cross-test mutation. AddEmittedMissingFrameworkBaseLibrary/EmitAssembly build in-memory PE images (MemoryStream) with no filesystem I/O. No [ResourceLock], [DoNotParallelize], lifecycle member, or fixture-declaration changes are present in the diff.

Audited MSTest.Analyzers.UnitTests at scope MethodLevel ([assembly: Parallelize(Scope = ExecutionScope.MethodLevel, Workers = 0)] in Program.cs), workers CPU count. Opt-in is attribute-based, so it is in scope for the MSTEST0074–MSTEST0077 parallel-safety analyzers (now on main), which found no issues either.

Advisory only — heuristic, non-blocking. Re-run with /parallel-audit.

🤖 Automated content by GitHub Copilot. Generated by the Parallel-safety audit on PR (on open / sync) workflow. · auto · 55.1 AIC · ⌖ 4.87 AIC · ⊞ 24.8K · [◷]( · ◷)

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Expert test review — PR #10508

Reviewed the single changed test file: test/UnitTests/MSTest.Analyzers.UnitTests/InheritedMemberFromDifferentMSTestVersionAnalyzerTests.cs (new, 56 [TestMethod]s covering the new InheritedMemberFromDifferentMSTestVersionAnalyzer, MSTEST0082).

This is a very thorough, high-quality suite. Highlights:

  • Every "Diagnostic" test asserts exact .WithArguments(member, baseType, attributeName, assemblyName), not just diagnostic presence — strong effectiveness.
  • Systematic edge-case coverage: shadowing by same/different signature, new hiding, generics (inferable/uninferable type parameters, renamed type parameters), visibility (internal/DiscoverInternals), overrides through multi-level chains, Task/ValueTask/Task<T> return shapes, abstract/generic-container test classes, and both project-reference and emitted-PE-with-missing-dependency shapes for the legacy framework.
  • Two NoDiagnostic tests (WhenInheritedClassInitializeFromEmittedMissingFrameworkPe, WhenInheritedClassCleanupFromEmittedMissingFrameworkPe) explicitly encode a documented analyzer limitation (undecodable InheritanceBehavior constructor argument) rather than silently under-testing it.
  • VB parity tests (...InVisualBasic_Diagnostic/_NoDiagnostic) confirm the analyzer is language-agnostic since it works on symbols.
  • Each test has a one-to-two-line comment stating the exact behavior/rationale under test, aiding maintainability and diagnosability of failures.
GradeTestMutationNotesHow to improve
A (90–100) new InheritedMemberFromDifferentMSTestVersionAnalyzerTests.
*
(all 56 tests)
N/A (asserted exact diagnostic arguments per test) Consistent, precise `.WithArguments` assertions; deliberate positive/negative pairing per edge case; documented known limitations are tested rather than ignored. —

No high-confidence actionable findings were identified; no inline suggestions were posted.

This advisory comment was generated automatically. Grades are heuristic and informational — they do not block merging. Re-run with /review-tests.

🤖 Automated content by GitHub Copilot. Generated by the Test Reviewer on PR (on open / sync) workflow. · auto · 139.3 AIC · ⌖ 5.83 AIC · ⊞ 16.9K · [◷]( · ◷)

@nohwnd
Jakub Jareš (nohwnd) merged commit dc84cc9 into main Aug 11, 2026
33 checks passed
@nohwnd
Jakub Jareš (nohwnd) deleted the nohwnd-curly-guide branch August 11, 2026 08:20
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.

4 participants