Community程式設計與開發github.com

CRAP 分析

分析程式碼涵蓋率與 CRAP(變更風險反模式)分數,識別高風險程式碼。使用 OpenCover 格式與 ReportGenerator 產生的風險熱點報表,呈現循環複雜度與未測試的程式碼路徑。

CRAP 分析 是什麼?

這個技能(crap-analysis)幫助開發者與 AI 代理分析 .NET 專案的程式碼品質,透過 CRAP(Change Risk Anti-Patterns)分數找出高風險的程式碼。CRAP 分數結合循環複雜度與測試涵蓋率,計算公式為:複雜度 × (1 - 涵蓋率)²。分數低於 5 表示低風險,5-30 為中等風險,超過 30 則需要立即測試或重構。 該技能支援使用 OpenCover 格式收集程式碼涵蓋率(必須包含此格式才能取得複雜度指標),並透過 ReportGenerator 工具產生包含「風險熱點」區段的 HTML 報表。報表會依複雜度排序方法,並顯示 CRAP 分數,幫助團隊優先處理最危險的程式碼。 此外,它也提供完整的 CI/CD 整合範例(GitHub Actions 與 Azure Pipelines)、推薦的涵蓋率閾值(行涵蓋率 >80%、分支涵蓋率 >60%、CRAP 分數 <30),以及需要排除的檔案模式(測試組件、產生的程式碼、Blazor 元件、EF Core 遷移等)。支援 Cursor、Claude Code 或 Codex 等 AI 代理工具,適合在程式碼審查、重構規劃或 CI 管道中自動化使用。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/crap-analysis

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

CRAP 分數分析

使用時機

在以下情況使用此技能:

  • 在進行變更前評估程式碼品質與測試涵蓋率
  • 識別需要重構或測試的高風險程式碼
  • 為 .NET 專案設定涵蓋率收集
  • 根據風險優先排序需測試的程式碼
  • 為 CI/CD 管道建立涵蓋率閾值

什麼是 CRAP?

CRAP 分數 = 複雜度 × (1 - 涵蓋率)²

CRAP(變更風險反模式)分數結合循環複雜度與測試涵蓋率,以識別有風險的程式碼。

CRAP 分數風險等級需採取的行動
< 5低測試良好、可維護的程式碼
5-30中可接受,但需留意複雜度
> 30高需要測試或重構

為什麼 CRAP 很重要

  • 高複雜度 + 低涵蓋率 = 危險:難以理解且未經測試的程式碼,修改起來很危險
  • 僅靠複雜度不夠:一個 100% 涵蓋率的複雜方法,比一個 0% 涵蓋率的簡單方法更安全
  • 聚焦努力:優先測試複雜的程式碼,而非簡單的 getter/setter

CRAP 分數範例

方法複雜度涵蓋率計算CRAP
GetUserId()10%1 x (1 - 0)²1
ParseToken()5452%54 x (1 - 0.52)²12.4
ValidateForm()200%20 x (1 - 0)²20
ProcessOrder()4520%45 x (1 - 0.20)²28.8
ImportData()8010%80 x (1 - 0.10)²64.8

涵蓋率收集設定

coverage.runsettings

在儲存庫根目錄中建立 coverage.runsettings 檔案。必須使用 OpenCover 格式才能計算 CRAP 分數,因為它包含循環複雜度指標。

<?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="XPlat code coverage">
        <Configuration>
          <!-- OpenCover 格式包含 CRAP 分數所需的循環複雜度 -->
          <Format>cobertura,opencover</Format>

          <!-- 排除測試和基準測試組件 -->
          <Exclude>[*.Tests]*,[*.Benchmark]*,[*.Migrations]*</Exclude>

          <!-- 排除產生的程式碼、已淘汰成員和明確排除的項目 -->
          <ExcludeByAttribute>Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute,ExcludeFromCodeCoverageAttribute</ExcludeByAttribute>

          <!-- 排除來源產生的檔案、Blazor 產生的程式碼和遷移 -->
          <ExcludeByFile>**/obj/**/*,**/*.g.cs,**/*.designer.cs,**/*.razor.g.cs,**/*.razor.css.g.cs,**/Migrations/**/*</ExcludeByFile>

          <!-- 排除測試專案 -->
          <IncludeTestAssembly>false</IncludeTestAssembly>

          <!-- 最佳化旗標 -->
          <SingleHit>false</SingleHit>
          <UseSourceLink>true</UseSourceLink>
          <SkipAutoProps>true</SkipAutoProps>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>

重要設定選項

選項用途
Format必須包含 opencover 以取得複雜度指標
Exclude依模式排除測試/基準測試組件
ExcludeByAttribute跳過產生的、已淘汰的和明確排除的程式碼(包含 ExcludeFromCodeCoverageAttribute)
ExcludeByFile跳過來源產生的檔案、Blazor 元件和遷移
SkipAutoProps不將自動屬性視為分支

ReportGenerator 安裝

將 ReportGenerator 安裝為本機工具,以產生包含風險熱點的 HTML 報表。

加入 .config/dotnet-tools.json

{
  "version": 1,
  "isRoot": true,
  "tools": {
    "dotnet-reportgenerator-globaltool": {
      "version": "5.4.5",
      "commands": ["reportgenerator"],
      "rollForward": false
    }
  }
}

然後還原:

dotnet tool restore

或全域安裝

dotnet tool install --global dotnet-reportgenerator-globaltool

收集涵蓋率

使用涵蓋率收集執行測試

# 清除先前的結果
rm -rf coverage/ TestResults/

# 使用涵蓋率執行單元測試
dotnet test tests/MyApp.Tests.Unit \
  --settings coverage.runsettings \
  --collect:"XPlat Code Coverage" \
  --results-directory ./TestResults

# 執行整合測試(可選,增加涵蓋率)
dotnet test tests/MyApp.Tests.Integration \
  --settings coverage.runsettings \
  --collect:"XPlat Code Coverage" \
  --results-directory ./TestResults

產生 HTML 報表

dotnet reportgenerator \
  -reports:"TestResults/**/coverage.opencover.xml" \
  -targetdir:"coverage" \
  -reporttypes:"Html;TextSummary;MarkdownSummaryGithub"

報表類型

類型說明輸出
Html完整互動式報表coverage/index.html
TextSummary純文字摘要coverage/Summary.txt
MarkdownSummaryGithubGitHub 相容的 Markdowncoverage/SummaryGithub.md
Badges適用於 README 的 SVG 徽章coverage/badge_*.svg
Cobertura合併的 Cobertura XMLcoverage/Cobertura.xml

閱讀報表

風險熱點區段

HTML 報表包含一個風險熱點區段,顯示依複雜度排序的方法:

  • 循環複雜度:程式碼中獨立路徑的數量(if/else、switch 情況、迴圈)
  • NPath 複雜度:非循環執行路徑的數量(會隨巢狀結構指數成長)
  • CRAP 分數:根據複雜度和涵蓋率計算得出

解讀結果

風險熱點
─────────────
方法                          複雜度  涵蓋率  CRAP 分數
─────────────────────────────────────────────────────────
DataImporter.ParseRecord()      54       52%       12.4
AuthService.ValidateToken()     32       0%        32.0   ← 高風險
OrderProcessor.Calculate()      28       85%       1.3
UserService.CreateUser()        15       100%      0.0

需採取的行動:

  • ValidateToken() 的 CRAP 分數 > 30 且涵蓋率為 0% - 立即測試或重構
  • ParseRecord() 很複雜但涵蓋率不錯 - 可接受
  • CreateUser() 和 Calculate() 測試良好 - 修改安全

涵蓋率閾值

建議標準

涵蓋率類型目標行動
行涵蓋率> 80%對大多數專案來說很好
分支涵蓋率> 60%能捕捉條件邏輯
CRAP 分數< 30新程式碼的上限

設定閾值

在儲存庫中建立 coverage.props:

<Project>
  <PropertyGroup>
    <!-- 用於 CI 強制執行的涵蓋率閾值 -->
    <CoverageThresholdLine>80</CoverageThresholdLine>
    <CoverageThresholdBranch>60</CoverageThresholdBranch>
  </PropertyGroup>
</Project>

CI/CD 整合

GitHub Actions

name: Coverage

on:
  pull_request:
    branches: [main, dev]

jobs:
  coverage:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '9.0.x'

      - name: Restore tools
        run: dotnet tool restore

      - name: Run tests with coverage
        run: |
          dotnet test \
            --settings coverage.runsettings \
            --collect:"XPlat Code Coverage" \
            --results-directory ./TestResults

      - name: Generate report
        run: |
          dotnet reportgenerator \
            -reports:"TestResults/**/coverage.opencover.xml" \
            -targetdir:"coverage" \
            -reporttypes:"Html;MarkdownSummaryGithub;Cobertura"

      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage/

      - name: Add coverage to PR
        uses: marocchino/sticky-pull-request-comment@v2
        with:
          path: coverage/SummaryGithub.md

Azure Pipelines

- task: DotNetCoreCLI@2
  displayName: '使用涵蓋率執行測試'
  inputs:
    command: 'test'
    arguments: '--settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory $(Build.SourcesDirectory)/TestResults'

- task: DotNetCoreCLI@2
  displayName: '產生涵蓋率報表'
  inputs:
    command: 'custom'
    custom: 'reportgenerator'
    arguments: '-reports:"$(Build.SourcesDirectory)/TestResults/**/coverage.opencover.xml" -targetdir:"$(Build.SourcesDirectory)/coverage" -reporttypes:"HtmlInline_AzurePipelines;Cobertura"'

- task: PublishCodeCoverageResults@2
  displayName: '發佈涵蓋率'
  inputs:
    codeCoverageTool: 'Cobertura'
    summaryFileLocation: '$(Build.SourcesDirectory)/coverage/Cobertura.xml'

快速參考

單行命令

# 完整分析工作流程
rm -rf coverage/ TestResults/ && \
dotnet test --settings coverage.runsettings \
  --collect:"XPlat Code Coverage" \
  --results-directory ./TestResults && \
dotnet reportgenerator \
  -reports:"TestResults/**/coverage.opencover.xml" \
  -targetdir:"coverage" \
  -reporttypes:"Html;TextSummary"

# 檢視摘要
cat coverage/Summary.txt

# 開啟 HTML 報表(Linux)
xdg-open coverage/index.html

# 開啟 HTML 報表(macOS)
open coverage/index.html

# 開啟 HTML 報表(Windows)
start coverage/index.html

專案標準

指標新程式碼舊程式碼
行涵蓋率80%+60%+(逐步改善)
分支涵蓋率60%+40%+(逐步改善)
最大 CRAP30記錄例外情況
高風險方法必須有測試修改前先加入測試

什麼會被排除

建議的 coverage.runsettings 會排除:

模式原因
[*.Tests]*測試組件不是生產程式碼
[*.Benchmark]*基準測試專案
[*.Migrations]*資料庫遷移(產生的)
GeneratedCodeAttribute原始碼產生器
CompilerGeneratedAttribute編譯器產生的程式碼
ExcludeFromCodeCoverageAttribute開發者明確選擇退出
*.g.cs, *.designer.cs產生的檔案
*.razor.g.csBlazor 元件產生的程式碼
*.razor.css.g.csBlazor CSS 隔離產生的程式碼
**/Migrations/**/*EF Core 遷移(自動產生)
SkipAutoProps自動屬性(瑣碎的分支)

何時更新閾值

暫時降低閾值的情況:

  • 正在現代化的舊程式碼基底(在 README 中記錄)
  • 無法修改的產生程式碼
  • 第三方包裝程式碼

永遠不要降低閾值的情況:

  • 「測試太難了」- 改成重構
  • 「我們稍後再補測試」- 現在就補上
  • 新功能 - 從一開始就應符合標準

其他資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能