Skip to content

[duplicate-code] Repeated Contains/throw validation blocks in eng/validate-affected-tests.ps1 #11510

Closed as not planned

Description

@github-actions

Analysis of commit acf0a07 ("Prepare affected-test selection CI", #11364)

Assignee: @copilot

Summary

The commit substantially expanded eng/validate-affected-tests.ps1 (from ~150 to 229 lines) by adding many structurally identical "assert substring present, otherwise throw" checks. The same two micro-patterns are copy-pasted repeatedly instead of being extracted into small reusable helper functions, making the script harder to read and maintain, and increasing the chance that future additions diverge in behavior (e.g. inconsistent negation, message wording, or missed checks).

Duplication Details

Pattern 1: Single if (-not $text.Contains(literal)) { throw "..." } block

  • Severity: Medium
  • Occurrences: 4+ (this commit added at least 4 new instances of this exact shape)
  • Locations (eng/validate-affected-tests.ps1):
    • lines 80–83
    • lines 84–87
    • lines 91–94
    • lines 95–98
  • Code Sample:
    if (-not $directoryPackages.Contains(
        '<PackageVersion Include="Microsoft.Testing.Extensions.AffectedTests" Version="$(MicrosoftTestingExtensionsCodeCoverageVersion)" />')) {
        throw "Directory.Packages.props must align Microsoft.Testing.Extensions.AffectedTests with the CodeCoverage dependency."
    }
    if (-not $directoryPackages.Contains(
        '<PackageVersion Include="Microsoft.Testing.Extensions.AffectedTests.Storage.AzureDevOps" Version="$(MicrosoftTestingExtensionsCodeCoverageVersion)" />')) {
        throw "Directory.Packages.props must align the Azure DevOps affected-tests provider with the CodeCoverage dependency."
    }
    if (-not $directoryBuildTargets.Contains(
        '<PackageReference Include="Microsoft.Testing.Extensions.AffectedTests"')) {
        throw "MTP test applications must reference Microsoft.Testing.Extensions.AffectedTests."
    }
    if (-not $directoryBuildTargets.Contains(
        '<PackageReference Include="Microsoft.Testing.Extensions.AffectedTests.Storage.AzureDevOps"')) {
        throw "MTP test applications must reference the Azure DevOps affected-tests storage provider."
    }

Pattern 2: foreach ($item in @(...)) { if (-not $text.Contains($item)) { throw ... } } loop

  • Severity: Medium
  • Occurrences: 4 (near-identical loop shape, varying only the haystack variable, item list, and message template)
  • Locations:
    • lines 99–107 ($testApplicationProperty over $directoryBuildTargets)
    • lines 125–140 ($requiredText over $testTemplate)
    • lines 155–163 ($variableName over $outerPipelineConfiguration, inverted condition)
    • lines 180–188 ($variableName over $wellKnownEnvironmentVariables)
  • Code Sample:
    foreach ($requiredText in @(
        "DOTNET_CLI_ENABLE_AFFECTED_TESTS: 1",
        'CTS_ACCESSTOKEN: $(System.AccessToken)',
        ...
    )) {
        if (-not $testTemplate.Contains($requiredText)) {
            throw "The affected-test template is missing '$requiredText'."
        }
    }
    
    foreach ($variableName in @(
        "DOTNET_CLI_ENABLE_AFFECTED_TESTS",
        "DOTNET_CLI_TEST_AFFECTED_TESTS_MODE",
        "TESTINGPLATFORM_EXITCODE_IGNORE"
    )) {
        if (-not $wellKnownEnvironmentVariables.Contains("""$variableName""")) {
            throw "Child test processes must not inherit $variableName from the outer pipeline invocation."
        }
    }

Impact Analysis

  • Maintainability: Every new "must contain X" rule requires copy-pasting a 3–4 line block instead of a single call; inconsistent phrasing/negation already exists across occurrences (e.g. line 160 inverts the polarity: if ($outerPipelineConfiguration.Contains(...)) { throw ... } vs. the -not form elsewhere), making the script harder to scan and audit.
  • Bug Risk: Because each block is hand-copied, a future edit could silently omit the -not, miss updating the message, or check the wrong variable — this class of mistake is exactly what a shared helper prevents by construction.
  • Code Bloat: The duplicated shape accounts for roughly 40+ of the script's 229 lines.

Refactoring Recommendations

  1. Extract an Assert-Contains helper

    • Add near the top of eng/validate-affected-tests.ps1:
      function Assert-Contains {
          param([string]$Text, [string]$Substring, [string]$Message)
          if (-not $Text.Contains($Substring)) {
              throw $Message
          }
      }
    • Estimated effort: ~30 minutes
    • Benefits: Collapses Pattern 1's 4 blocks (16 lines) into 4 one-line calls; keeps the throw message explicit at the call site.
  2. Extract an Assert-AllContain helper for the foreach loops

    • Add:
      function Assert-AllContain {
          param([string]$Text, [string[]]$Substrings, [scriptblock]$MessageFormatter)
          foreach ($substring in $Substrings) {
              if (-not $Text.Contains($substring)) {
                  throw (& $MessageFormatter $substring)
              }
          }
      }
    • Apply at the four foreach locations (lines 99–107, 125–140, 155–163, 180–188), passing a message-formatting scriptblock per call site.
    • Estimated effort: ~1 hour (including verifying the inverted-condition call site at lines 155–163 is translated correctly, e.g. via an Assert-NoneContain counterpart or an explicit -Invert switch).
    • Benefits: Collapses ~50 lines of near-identical loop bodies into 4 short calls; centralizes the "missing required text" and "must not contain" failure semantics so future checks are added consistently.

Implementation Checklist

  • Review duplication findings
  • Prioritize refactoring tasks
  • Create refactoring plan
  • Implement changes
  • Update tests
  • Verify no functionality broken (re-run eng/validate-affected-tests.ps1 and confirm all existing throw conditions still fire correctly)

Analysis Metadata

  • Analyzed Files: eng/validate-affected-tests.ps1 (primary), cross-referenced against other files changed in commit acf0a07
  • Detection Method: Semantic code analysis (structural comparison of if/foreach + Contains/throw blocks)
  • Commit: acf0a07
  • Analysis Date: 2026-09-25

🤖 Automated content by GitHub Copilot. Generated by the Duplicate Code Detector workflow. · copilot · auto · 76.6 AIC · ⌖ 5.28 AIC · ⊞ 13.4K · [◷]( · ◷)

Add this agentic workflow to your repo

To install this agentic workflow, run

gh aw add githubnext/agentics/workflows/duplicate-code-detector.md@main
  • expires on Sep 27, 2026, 4:33 AM UTC

Activity

  1. github-actions commented on Sep 27, 2026

    @github-actions
    ContributorAuthor

    This issue was automatically closed because it expired on 2026-09-27T04:33:31.254Z.

    Closed by Workflow

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

Metadata

Metadata

Labels

type/automationCreated or maintained by an agentic workflow.type/tech-debtCode health, refactoring, simplification.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions