Skip to content

[duplicate-code] Duplicate Code: AssemblyInitialize/AssemblyCleanup AnalyzeSymbol Pattern in Fixture Analyzers #9491

Closed

Description

Analysis of commit a80cd31

Assignee: @copilot

Summary

AssemblyInitializeShouldBeValidAnalyzer and AssemblyCleanupShouldBeValidAnalyzer contain near-identical AnalyzeSymbol methods (~10–14 lines each). Like the TestInitialize/TestCleanup pair addressed in PR #9485, these two analyzers differ only in FixtureParameterMode (MustHaveTestContext vs OptionalTestContext) but share all other static-fixture validation logic. A parallel helper can eliminate this duplication.

Duplication Details

Pattern: Near-identical assembly-level fixture AnalyzeSymbol methods

  • Severity: Medium
  • Occurrences: 2 instances
  • Locations:
    • src/Analyzers/MSTest.Analyzers/AssemblyInitializeShouldBeValidAnalyzer.cs (lines 45–57)
    • src/Analyzers/MSTest.Analyzers/AssemblyCleanupShouldBeValidAnalyzer.cs (lines 44–61)

AssemblyInitializeShouldBeValidAnalyzer.AnalyzeSymbol:

private static void AnalyzeSymbol(SymbolAnalysisContext context, FixtureMethodAnalyzerHelper.FixtureMethodSymbols symbols)
{
    var methodSymbol = (IMethodSymbol)context.Symbol;
    if (methodSymbol.HasAttribute(symbols.FixtureAttributeSymbol)
        && !methodSymbol.HasValidFixtureMethodSignature(symbols.TaskSymbol, symbols.ValueTaskSymbol, symbols.CanDiscoverInternals, shouldBeStatic: true,
            allowGenericType: false, FixtureParameterMode.MustHaveTestContext, symbols.TestContextSymbol,
            symbols.TestClassAttributeSymbol, fixtureAllowInheritedTestClass: false, out bool isFixable))
    {
        context.ReportDiagnostic(isFixable
            ? methodSymbol.CreateDiagnostic(Rule, methodSymbol.Name)
            : methodSymbol.CreateDiagnostic(Rule, DiagnosticDescriptorHelper.CannotFixProperties, methodSymbol.Name));
    }
}

AssemblyCleanupShouldBeValidAnalyzer.AnalyzeSymbol: same logic with FixtureParameterMode.OptionalTestContext and a minor structural difference (early-return guard for !HasAttribute).

Shared constant parameters across both:

  • shouldBeStatic: true
  • allowGenericType: false
  • fixtureAllowInheritedTestClass: false
  • Identical diagnostic reporting with isFixable ternary

Impact Analysis

  • Maintainability: Any future change to assembly-level fixture validation (e.g., supporting new parameter patterns) must be made twice. The isFixable ternary diagnostic reporting block is duplicated across both files and FixtureMethodAnalyzerHelper.
  • Bug Risk: High — structural differences in the early-return guard style between the two files mean that future modifications could introduce divergence.
  • Code Bloat: ~13 lines of functionally duplicated code across 2 files.

Refactoring Recommendations

  1. Add RegisterAssemblyFixtureAnalyzer helper to FixtureMethodAnalyzerHelper
    • Extract the common logic into:
      internal static void RegisterAssemblyFixtureAnalyzer(
          AnalysisContext context,
          string fixtureAttributeMetadataName,
          DiagnosticDescriptor rule,
          FixtureParameterMode parameterMode)
          => RegisterFixtureMethodSymbolAction(
              context,
              fixtureAttributeMetadataName,
              static (symbolContext, symbols, state) => AnalyzeAssemblyFixtureMethod(symbolContext, symbols, state.rule, state.parameterMode),
              (rule, parameterMode),
              requireTestContextSymbol: parameterMode == FixtureParameterMode.MustHaveTestContext);
    • Add the shared AnalyzeAssemblyFixtureMethod private method:
      internal static void AnalyzeAssemblyFixtureMethod(
          SymbolAnalysisContext context,
          FixtureMethodSymbols symbols,
          DiagnosticDescriptor rule,
          FixtureParameterMode parameterMode)
      {
          var methodSymbol = (IMethodSymbol)context.Symbol;
          if (methodSymbol.HasAttribute(symbols.FixtureAttributeSymbol)
              && !methodSymbol.HasValidFixtureMethodSignature(symbols.TaskSymbol, symbols.ValueTaskSymbol,
                  symbols.CanDiscoverInternals, shouldBeStatic: true,
                  allowGenericType: false, parameterMode, symbols.TestContextSymbol,
                  symbols.TestClassAttributeSymbol, fixtureAllowInheritedTestClass: false, out bool isFixable))
          {
              context.ReportDiagnostic(isFixable
                  ? methodSymbol.CreateDiagnostic(rule, methodSymbol.Name)
                  : methodSymbol.CreateDiagnostic(rule, DiagnosticDescriptorHelper.CannotFixProperties, methodSymbol.Name));
          }
      }
    • Update AssemblyInitializeShouldBeValidAnalyzer.Initialize to:
      FixtureMethodAnalyzerHelper.RegisterAssemblyFixtureAnalyzer(
          context,
          WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyInitializeAttribute,
          Rule,
          FixtureParameterMode.MustHaveTestContext);
    • Update AssemblyCleanupShouldBeValidAnalyzer.Initialize similarly with FixtureParameterMode.OptionalTestContext.
    • Remove the private AnalyzeSymbol methods from both analyzer classes.
    • Estimated effort: ~1 hour
    • Benefits: Eliminates duplicated assembly-fixture validation; aligns with the instance-fixture refactoring pattern from PR Refactor TestInitialize/TestCleanup analyzer registration into shared fixture helper #9485; normalizes the minor structural divergence between the two AnalyzeSymbol implementations.

Implementation Checklist

  • Review duplication findings
  • Add AnalyzeAssemblyFixtureMethod and RegisterAssemblyFixtureAnalyzer to src/Analyzers/MSTest.Analyzers/Helpers/FixtureMethodAnalyzerHelper.cs
  • Update AssemblyInitializeShouldBeValidAnalyzer.Initialize to delegate to the new helper
  • Update AssemblyCleanupShouldBeValidAnalyzer.Initialize to delegate to the new helper
  • Remove private AnalyzeSymbol methods from both analyzer classes
  • Verify analyzer tests still pass
  • Verify no functionality broken

Analysis Metadata

  • Analyzed Files: AssemblyInitializeShouldBeValidAnalyzer.cs, AssemblyCleanupShouldBeValidAnalyzer.cs, FixtureMethodAnalyzerHelper.cs
  • Detection Method: Semantic code analysis — structural similarity following the TestInitialize/TestCleanup refactoring
  • Commit: a80cd31
  • Analysis Date: 2026-06-29

🤖 Automated content by GitHub Copilot. Posted via a maintainer's GitHub token, so it appears under their account — the account owner did not write or approve this content personally. Generated by the Duplicate Code Detector workflow. · 530.8 AIC · ⌖ 25 AIC · ⊞ 43.6K · [◷]( · ◷)

Add this agentic workflows to your repo

To install this agentic workflow, run

gh aw add githubnext/agentics/workflows/duplicate-code-detector.md@main
  • expires on Jul 1, 2026, 5:57 AM UTC

Activity

  1. added
    type/tech-debt
    type/automation
    on Jun 29, 2026
  2. Evangelink commented on Jun 29, 2026

    @Evangelink
    MemberAuthor

    This was resolved by #9493 (Deduplicate assembly fixture analyzer validation), which is merged into main.

    AssemblyInitializeShouldBeValidAnalyzer and AssemblyCleanupShouldBeValidAnalyzer now delegate to FixtureMethodAnalyzerHelper.RegisterAssemblyFixtureAnalyzer.

    The analyzed duplication is no longer present in the codebase, so closing as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

type/automationtype/tech-debt

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions