Repository navigation
Detect inherited fixtures/tests from a different MSTest version (MSTEST0082) - #10508
Conversation
…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]>
There was a problem hiding this comment.
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. |
Amaury Levé (Evangelink)
left a comment
There was a problem hiding this comment.
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]>
|
Addressed the automated review as well (3998b0c):
13 tests, all green. 🤖 |
There was a problem hiding this comment.
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
TestContextshape (seeMethodInfoExtensions.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
AssemblyInitializeandAssemblyCleanup, 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
TestContextparameter (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 legacyTestContexttype 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]>
|
Second pass (8555a7f), addressing the follow-up review:
15 tests, all green; analyzer builds clean (0 warnings). 🤖 |
There was a problem hiding this comment.
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 returnstruefor 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 asTask/ValueTask, and it acceptsasync voidthroughReturnsVoid. The adapter rejects all three shapes, so this rule can warn even though recompiling the base would not make the member runnable. Please use exactTask/ValueTasksymbol equality and exclude asyncvoid, asFixtureUtils.HasValidTestMethodSignature/HasValidFixtureMethodSignaturealready 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
HasClassFixtureParameterShapeallows zero parameters for both class fixture kinds, but the adapter requires[ClassInitialize]to take exactly oneTestContext; 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
AssemblyInitializeandAssemblyCleanup, 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,
This comment has been minimized.
This comment has been minimized.
Amaury Levé (Evangelink)
left a comment
There was a problem hiding this comment.
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.
Amaury Levé (Evangelink)
left a comment
There was a problem hiding this comment.
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.
-
Missing legacy PE metadata can hide inherited class fixtures.
HasBeforeEachDerivedClassBehaviordepends on decodedAttributeData.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 explicitBeforeEachDerivedClassclass initialize/cleanup therefore escapes MSTEST0082. The current project-reference test covers only[TestInitialize]and preserves dependency symbols. Add an emitted-PE test withMetadataReference.CreateFromImage; complete support requires metadata-blob decoding, otherwise document/limit this scope. Existing thread:InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:228. -
Any same-name derived method suppresses a real warning.
IsHiddenOrOverriddenInDerivedTypetreats every derived method with the same name as a replacement. The adapter is kind-specific: an invalid/privateInitialize(int)does not suppress baseInitialize(), 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. -
Invalid return types pass analyzer validation. Name-only matching accepts
Task<T>andValueTask<T>, whileReturnsVoidalso acceptsasync void/VBAsync Sub. The adapter requires exact non-genericTask/ValueTaskand rejects asynchronous void. Resolve the task symbols at compilation start, compare withSymbolEqualityComparer.Default, and require!method.IsAsyncfor void. Existing current-head automated finding: line 217. -
ClassInitializeandClassCleanupparameter rules are conflated. The sharedClassFixturebranch allows zero or oneTestContext, but initialize requires exactly one while cleanup permits zero or one. Preserve distinct member kinds and add a no-diagnostic test for parameterless legacyClassInitialize. 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]>
There was a problem hiding this comment.
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>, andValueTask<T>because it checks onlyReturnsVoidor 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-asyncvoidand arity-zeroTask/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
ClassInitializeandClassCleanupcannot share this parameter check. MSTest requiresClassInitializeto take exactly oneTestContext(MethodInfoExtensions.cs:20-30andClassInitializeShouldBeValidAnalyzer.cs:37-41), whereas onlyClassCleanupmay 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)
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
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]>
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
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
GetRuntimeMethodsdelegates toType.GetMethods(Everything)(ReflectionOperations.cs:68-69), which removes a base method hidden by a same-signature derived declaration beforeTestMethodValidatorexamines attributes. Requiring the derived method itself to be discoverable therefore produces a false MSTEST0082 for cases such aspublic new void Run()without[TestMethod]: the legacy baseRunis absent both before and after recompilation. Treat any same-signature derived method as hiding the base method, and update the correspondingWhenInheritedTestMethodShadowedByNonTestMethod_Diagnosticexpectation.
case MSTestMemberKind.TestMethod
when IsDiscoverableTestMethod(derivedMethod, referenceAssembly, canDiscoverInternals, taskSymbol, valueTaskSymbol)
&& HaveSameSignature(derivedMethod, baseMethod):
This comment has been minimized.
This comment has been minimized.
Jan Krivanek (JanKrivanek)
left a comment
There was a problem hiding this comment.
Code looks good to go at head 824705c9; no major correctness, API, or test-coverage concerns found.
Amaury Levé (Evangelink)
left a comment
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
truewhenAttributeUsagecannot 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 hasInherited=false, so recompiling the base still leaves the override undiscoverable, but this code reports MSTEST0082. Preserve the knownInherited=falsesemantics for unresolved standardTestMethod,TestInitialize, andTestCleanupattributes, 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,
TypeValidatorrejects a concrete test class nested in a generic container and a class with an invalid declaredTestContextgetter; the existing runnable-class check inDependsOnShouldBeValidAnalyzerhandles both cases. Please reuse equivalent test-class validation here before reporting MSTEST0082.
if (!classSymbol.IsTestClass(testClassAttributeSymbol)
|| classSymbol.IsAbstract
|| classSymbol.IsGenericType
|| !IsDiscoverableTestClassVisibility(classSymbol, canDiscoverInternals))
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
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
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
There was a problem hiding this comment.
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.IsValidTestMethodShouldReturnTrueForGenericTestMethodDefinitionsandGenericTestMethodTests, lines 26-27). For a legacy inheritedRun<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 inIsDiscoverableTestMethod, and update the correspondingNoDiagnostictest.
MSTestMemberKind.TestMethod
=> !method.IsStatic
&& ReturnsVoidTaskOrValueTask(method, taskSymbol, valueTaskSymbol)
&& (!method.IsGenericMethod || AllGenericTypeParametersAreInferable(method)),
src/Analyzers/MSTest.Analyzers/InheritedMemberFromDifferentMSTestVersionAnalyzer.cs:350
continuecan 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 returnstrueand 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 returnfalseimmediately.
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 aTestContext-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 currentTestContextsymbol and mirror the existing check inDependsOnShouldBeValidAnalyzer.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))
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
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.TestInitializeAttributeinContoso.Helperswould 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.
WellKnownTypeProviderdeliberately 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 appliedTestClassattribute (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
There was a problem hiding this comment.
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
GetRuntimeMethodscallsType.GetMethodsbeforeTestMethodValidatorfilters attributes, so a derived method with the same CLR signature hides the base method even when the derived method is not itself a test. RequiringIsDiscoverableTestMethodhere therefore reports a false migration warning for thepublic 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)andRun<U>(U)have the same runtime signature and the derived method hides the base method before MSTest de-duplication; comparingNamemakes the analyzer incorrectly warn for the renamed-type-parameter test. CompareOrdinal(along withTypeParameterKind) 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 : TestMethodAttributeis compiled against v3 inCustomAttributes.dlland then applied inBaseLibrary.dll, rebuilding the assembly that declaresTestBaseleavesRetryTestAttributebased 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.TestInitializeAttributein 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))
{
🧵 Parallel-safety audit — PR #10508Nothing audited here touches process-global state, shared filesystem paths, or The only changed test file is Audited Advisory only — heuristic, non-blocking. Re-run with
|
🧪 Expert test review — PR #10508Reviewed the single changed test file: This is a very thorough, high-quality suite. Highlights:
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
|
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:Microsoft.VisualStudio.TestPlatform.TestFrameworkMSTest.TestFrameworkso 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/AssemblyCleanupare 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:
[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;TestContext-shaped class fixtures,void/Task/ValueTaskreturns), class fixtures only withInheritanceBehavior.BeforeEachDerivedClass, and members overridden or hidden withnewin a more-derived type are suppressed.It's a
SymbolKind.NamedTypeaction that early-outs viaIsTestClassand 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.🤖