jpskill.com
📦 その他 コミュニティ

coverage-analyzer

網羅率分析で未検証箇所を特定し、テストを提案、進捗を追跡、重要な未検証コードを強調することで、80%以上の網羅率目標達成を支援するSkill。

📜 元の英語説明(参考)

Advanced coverage analysis with actionable insights. Use to identify coverage gaps, suggest specific tests, track coverage trends, and highlight critical uncovered code. Essential for reaching 80%+ coverage target.

🇯🇵 日本人クリエイター向け解説

一言でいうと

網羅率分析で未検証箇所を特定し、テストを提案、進捗を追跡、重要な未検証コードを強調することで、80%以上の網羅率目標達成を支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o coverage-analyzer.zip https://jpskill.com/download/17339.zip && unzip -o coverage-analyzer.zip && rm coverage-analyzer.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17339.zip -OutFile "$d\coverage-analyzer.zip"; Expand-Archive "$d\coverage-analyzer.zip" -DestinationPath $d -Force; ri "$d\coverage-analyzer.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して coverage-analyzer.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → coverage-analyzer フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Coverage Analyzer

⚠️ 必須: 最初にプロジェクトドキュメントをお読みください

カバレッジ分析を開始する前に、以下のプロジェクトドキュメントを必ず読んで理解してください。

コアプロジェクトドキュメント

  1. README.md - プロジェクトの概要、機能、および始め方
  2. AI_DOCS/project-context.md - 技術スタック、アーキテクチャ、開発ワークフロー
  3. AI_DOCS/code-conventions.md - コードスタイル、フォーマット、ベストプラクティス
  4. AI_DOCS/tdd-workflow.md - TDDプロセス、テスト標準、カバレッジ要件

セッションコンテキスト(利用可能な場合)

  1. .ai-context/ACTIVE_TASKS.md - 現在のタスクと優先順位
  2. .ai-context/CONVENTIONS.md - プロジェクト固有の規約
  3. .ai-context/RECENT_DECISIONS.md - 最近のアーキテクチャに関する決定
  4. .ai-context/LAST_SESSION_SUMMARY.md - 前回のセッションの要約

追加のAIドキュメント

  1. AI_DOCS/ai-tools.md - セッション管理ワークフロー
  2. AI_DOCS/ai-skills.md - 利用可能なその他の専門スキル/エージェント

これが重要な理由

  • カバレッジ要件: プロジェクト固有のカバレッジ閾値(最低80%以上)を理解する
  • テストパターン: テストを提案する際に、確立されたテスト規約に従う
  • コードコンテキスト: モジュールの構造と依存関係を理解する
  • 最近の変更: 最近のテストの追加やカバレッジの改善を把握する

これらのファイルを読んだ後、以下のカバレッジ分析タスクに進んでください。


概要

80%以上の要件を満たすようにカバレッジを改善するための、実行可能な洞察を備えた高度なテストカバレッジ分析を提供します。

使用するタイミング

  • make coverageを実行してギャップを理解した後
  • 機能の完了前(十分なカバレッジを確保)
  • カバレッジが80%の目標を下回っている場合
  • カバーされていない重要なコードパスを特定するため
  • 時間経過に伴うカバレッジの傾向を追跡するため

このスキルが提供するもの

詳細なカバレッジ分析

  • 現在のカバレッジ率
  • ファイルごとのカバーされていない行
  • 不足している分岐

実行可能な推奨事項

  • 作成する特定のテスト
  • テストが必要なコードの場所
  • カバレッジギャップの優先度

カバレッジギャップの特定

  • カバーされていない重要なパス(エラー処理)
  • テストされていないエッジケース
  • テストが不足している統合ポイント

テストの提案

  • 具体的なテストコードの推奨事項
  • パラメータ化されたテストの提案
  • フィクスチャの推奨事項

トレンド追跡

  • 時間経過に伴うカバレッジの履歴
  • 改善/後退の検出
  • 80%以上の目標に向けた進捗

使用例

現在のカバレッジを分析する

# 詳細なカバレッジ分析を生成する
analyze test coverage

出力: ギャップと推奨事項を含む包括的なレポート

重要なギャップを見つける

# カバーされていない重要なコードに焦点を当てる
show critical coverage gaps

出力: 優先度の高いカバーされていないコード(エラー処理、セキュリティ、エッジケース)

テストの提案を得る

# 特定のテストの推奨事項を得る
suggest tests for uncovered code in src/python_modern_template/validators.py

出力: 追加する具体的なテストケース

カバレッジの傾向を追跡する

# 時間経過に伴うカバレッジを確認する
show coverage trend for last month

出力: カバレッジの変化を示すグラフ

ステップバイステップ分析プロセス

ステップ1:カバレッジの実行

# カバレッジレポートを生成する
make coverage

これにより、以下が作成されます。

  • 全体的な割合を示すターミナル出力
  • htmlcov/内のHTMLレポート
  • .coverageデータファイル

ステップ2:カバレッジデータの解析

複数のソースからカバレッジデータを読み取ります。

# 全体的な統計についてはターミナル出力を読み取る
# 詳細な内訳についてはhtmlcov/index.htmlを読み取る
# 行ごとのデータについては.coverageファイルを解析する

ステップ3:カバーされていない行の特定

ソースファイルごとに:

  • カバーされていない行番号をリストする
  • タイプ(関数、エラー処理、エッジケース)でグループ化する
  • 重要度で優先順位を付ける

ステップ4:コンテキストの分析

カバーされていないセクションごとに:

  • 周囲のコードを読む
  • コードが何をするかを理解する
  • カバーされていない理由を特定する
  • 適切なテストタイプを決定する

ステップ5:推奨事項の生成

具体的なテストの提案を作成します。

  • テスト関数名
  • テストシナリオ
  • テストコードの例
  • テストするパラメータ

ステップ6:優先度の計算

CRITICAL - すぐにカバーする必要がある:

  • エラー処理パス
  • セキュリティ関連のコード
  • データ検証
  • 認証チェック

HIGH - すぐにカバーする必要がある:

  • エッジケース
  • 境界条件
  • 統合ポイント
  • パブリックAPI関数

MEDIUM - カバーするのに適している:

  • 内部ヘルパー関数
  • ログステートメント
  • 構成解析

LOW - オプション:

  • デバッグコード
  • 開発専用パス
  • 非推奨の関数

分析レポートの形式

# テストカバレッジ分析

## エグゼクティブサマリー

**現在のカバレッジ:** 75.3%
**目標:** 80%+
**ギャップ:** 4.7%(23行がカバーされていません)
**ステータス:** ⚠️ 目標を下回っています

**内訳:**
- src/python_modern_template/:73.2%(18行がカバーされていません)
- tests/:100%(完全にカバーされています)

---

## 重要なギャップ(修正必須)

### 1. validators.pyのエラー処理 ⚠️ CRITICAL

**ファイル:** src/python_modern_template/validators.py
**行:** 45-52(8行)
**関数:** `validate_email()`

**カバーされていないコード:**
```python
45: except ValueError as e:
46:     logger.error(f"Email validation failed: {e}")
47:     raise ValidationError(
48:         "Invalid email format"
49:     ) from e
50: except Exception:
51:     logger.critical("Unexpected validation error")
52:     return False

重要な理由: エラー処理パスがテストされておらず、バグを隠す可能性があります

推奨されるテスト:

def test_validate_email_value_error_handling() -> None:
    """Test email validation handles ValueError correctly."""
    # Arrange
    invalid_email = "not-an-email"

    # Act & Assert
    with pytest.raises(ValidationError) as exc_info:
        validate_email(invalid_email)

    assert "Invalid email format" in str(exc_info.value)
    assert exc_info.value.__cause__ is not None

def test_validate_email_unexpected_error_handling() -> None:
    """Test email validation handles unexpected errors."""
    # Arrange
    # Mock to raise unexpected exc

(原文はここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Coverage Analyzer

⚠️ MANDATORY: Read Project Documentation First

BEFORE starting coverage analysis, you MUST read and understand the following project documentation:

Core Project Documentation

  1. README.md - Project overview, features, and getting started
  2. AI_DOCS/project-context.md - Tech stack, architecture, development workflow
  3. AI_DOCS/code-conventions.md - Code style, formatting, best practices
  4. AI_DOCS/tdd-workflow.md - TDD process, testing standards, coverage requirements

Session Context (if available)

  1. .ai-context/ACTIVE_TASKS.md - Current tasks and priorities
  2. .ai-context/CONVENTIONS.md - Project-specific conventions
  3. .ai-context/RECENT_DECISIONS.md - Recent architectural decisions
  4. .ai-context/LAST_SESSION_SUMMARY.md - Previous session summary

Additional AI Documentation

  1. AI_DOCS/ai-tools.md - Session management workflow
  2. AI_DOCS/ai-skills.md - Other specialized skills/agents available

Why This Matters

  • Coverage Requirements: Understand project-specific coverage thresholds (80%+ minimum)
  • Testing Patterns: Follow established testing conventions when suggesting tests
  • Code Context: Understand module structure and dependencies
  • Recent Changes: Be aware of recent test additions or coverage improvements

After reading these files, proceed with your coverage analysis task below.


Overview

Provide advanced test coverage analysis with actionable insights for improving coverage to meet the 80%+ requirement.

When to Use

  • After running make coverage to understand gaps
  • Before completing a feature (ensure adequate coverage)
  • When coverage is below 80% target
  • To identify critical uncovered code paths
  • For tracking coverage trends over time

What This Skill Provides

Detailed Coverage Analysis

  • Current coverage percentage
  • Uncovered lines by file
  • Missing branches

Actionable Recommendations

  • Specific tests to write
  • Code locations needing tests
  • Priority of coverage gaps

Coverage Gaps Identification

  • Critical uncovered paths (error handling)
  • Edge cases not tested
  • Integration points missing tests

Test Suggestions

  • Concrete test code recommendations
  • Parametrized test suggestions
  • Fixture recommendations

Trend Tracking

  • Coverage history over time
  • Improvement/regression detection
  • Progress toward 80%+ goal

Usage Examples

Analyze Current Coverage

# Generate detailed coverage analysis
analyze test coverage

Output: Comprehensive report with gaps and recommendations

Find Critical Gaps

# Focus on critical uncovered code
show critical coverage gaps

Output: High-priority uncovered code (error handling, security, edge cases)

Get Test Suggestions

# Get specific test recommendations
suggest tests for uncovered code in src/python_modern_template/validators.py

Output: Concrete test cases to add

Track Coverage Trends

# See coverage over time
show coverage trend for last month

Output: Graph showing coverage changes

Step-by-Step Analysis Process

Step 1: Run Coverage

# Generate coverage report
make coverage

This creates:

  • Terminal output with overall percentage
  • HTML report in htmlcov/
  • .coverage data file

Step 2: Parse Coverage Data

Read coverage data from multiple sources:

# Read terminal output for overall stats
# Read htmlcov/index.html for detailed breakdown
# Parse .coverage file for line-by-line data

Step 3: Identify Uncovered Lines

For each source file:

  • List uncovered line numbers
  • Group by type (functions, error handling, edge cases)
  • Prioritize by criticality

Step 4: Analyze Context

For each uncovered section:

  • Read surrounding code
  • Understand what the code does
  • Identify why it's not covered
  • Determine appropriate test type

Step 5: Generate Recommendations

Create specific test suggestions:

  • Test function name
  • Test scenario
  • Example test code
  • Parameters to test

Step 6: Calculate Priority

CRITICAL - Must cover immediately:

  • Error handling paths
  • Security-related code
  • Data validation
  • Authorization checks

HIGH - Should cover soon:

  • Edge cases
  • Boundary conditions
  • Integration points
  • Public API functions

MEDIUM - Good to cover:

  • Internal helper functions
  • Logging statements
  • Configuration parsing

LOW - Optional:

  • Debug code
  • Development-only paths
  • Deprecated functions

Analysis Report Format

# Test Coverage Analysis

## Executive Summary

**Current Coverage:** 75.3%
**Target:** 80%+
**Gap:** 4.7% (23 uncovered lines)
**Status:** ⚠️ Below target

**Breakdown:**
- src/python_modern_template/: 73.2% (18 uncovered lines)
- tests/: 100% (fully covered)

---

## Critical Gaps (MUST FIX)

### 1. Error Handling in validators.py ⚠️ CRITICAL

**File:** src/python_modern_template/validators.py
**Lines:** 45-52 (8 lines)
**Function:** `validate_email()`

**Uncovered Code:**
```python
45: except ValueError as e:
46:     logger.error(f"Email validation failed: {e}")
47:     raise ValidationError(
48:         "Invalid email format"
49:     ) from e
50: except Exception:
51:     logger.critical("Unexpected validation error")
52:     return False

Why Critical: Error handling paths are not tested, could hide bugs

Recommended Test:

def test_validate_email_value_error_handling() -> None:
    """Test email validation handles ValueError correctly."""
    # Arrange
    invalid_email = "not-an-email"

    # Act & Assert
    with pytest.raises(ValidationError) as exc_info:
        validate_email(invalid_email)

    assert "Invalid email format" in str(exc_info.value)
    assert exc_info.value.__cause__ is not None

def test_validate_email_unexpected_error_handling() -> None:
    """Test email validation handles unexpected errors."""
    # Arrange
    # Mock to raise unexpected exception
    with patch('validators.EMAIL_REGEX.match', side_effect=RuntimeError("Unexpected")):
        # Act
        result = validate_email("test@example.com")

        # Assert
        assert result is False

Impact: Covers 8 lines, adds 3.5% coverage


2. Edge Case in parser.py ⚠️ CRITICAL

File: src/python_modern_template/parser.py Lines: 67-70 (4 lines) Function: parse_config()

Uncovered Code:

67: if not config_data:
68:     logger.warning("Empty configuration provided")
69:     return DEFAULT_CONFIG
70:     # Unreachable line removed

Why Critical: Edge case handling not tested

Recommended Test:

def test_parse_config_empty_data() -> None:
    """Test parser handles empty configuration."""
    # Arrange
    empty_config = {}

    # Act
    result = parse_config(empty_config)

    # Assert
    assert result == DEFAULT_CONFIG

def test_parse_config_none_data() -> None:
    """Test parser handles None configuration."""
    # Arrange
    # Act
    result = parse_config(None)

    # Assert
    assert result == DEFAULT_CONFIG

Impact: Covers 4 lines, adds 1.7% coverage


High Priority Gaps

3. Integration Point in api_client.py

File: src/python_modern_template/api_client.py Lines: 112-118 (7 lines) Function: retry_with_backoff()

Uncovered Code:

112: @retry(max_attempts=3, backoff=2.0)
113: def retry_with_backoff(self, operation: Callable) -> Any:
114:     """Retry operation with exponential backoff."""
115:     try:
116:         return operation()
117:     except ConnectionError:
118:         logger.warning("Connection failed, retrying...")

Why High: Integration logic with retry mechanism

Recommended Test:

@pytest.mark.parametrize("attempt,should_succeed", [
    (1, True),  # Succeeds first try
    (2, True),  # Succeeds second try
    (3, True),  # Succeeds third try
    (4, False), # Fails after max attempts
])
def test_retry_with_backoff(attempt: int, should_succeed: bool) -> None:
    """Test retry mechanism with various scenarios."""
    # Arrange
    client = APIClient()
    call_count = 0

    def flaky_operation():
        nonlocal call_count
        call_count += 1
        if call_count < attempt:
            raise ConnectionError("Connection failed")
        return "success"

    # Act & Assert
    if should_succeed:
        result = client.retry_with_backoff(flaky_operation)
        assert result == "success"
        assert call_count == attempt
    else:
        with pytest.raises(ConnectionError):
            client.retry_with_backoff(flaky_operation)

Impact: Covers 7 lines, adds 3.0% coverage


Coverage By Module

Module Coverage Uncovered Lines Priority
validators.py 65% 12 CRITICAL
parser.py 80% 4 HIGH
api_client.py 75% 7 HIGH
utils.py 95% 1 LOW

Total: 75.3% (23 uncovered lines)


Quick Win Recommendations

These tests would quickly boost coverage:

  1. Add error handling tests (validators.py)

    • +3.5% coverage
    • 10 minutes to write
  2. Add edge case tests (parser.py)

    • +1.7% coverage
    • 5 minutes to write
  3. Add integration tests (api_client.py)

    • +3.0% coverage
    • 15 minutes to write

Total Impact: +8.2% coverage (reaching 83.5%) Total Time: ~30 minutes


Coverage Trend

Week 1: 70% ███████░░░
Week 2: 72% ███████▓░░
Week 3: 75% ████████░░
Week 4: 75% ████████░░  ← Current (stalled)

Target: 80% ████████▓░

Trend: +5% over 3 weeks, then stalled Recommendation: Focus on quick wins above to break through 80%


Detailed File Analysis

src/python_modern_template/validators.py (65% coverage)

Covered:

  • Basic email validation (happy path)
  • URL validation (happy path)
  • Phone number validation

Not Covered:

  • Error handling (lines 45-52)
  • Edge cases (empty strings, None)
  • Invalid format handling

Missing Test Types:

  • Parametrized tests for invalid inputs
  • Exception handling tests
  • Edge case tests

src/python_modern_template/parser.py (80% coverage)

Covered:

  • Standard config parsing
  • Type conversion
  • Default value handling

Not Covered:

  • Empty config handling (lines 67-70)

Missing Test Types:

  • Edge case tests (empty, None)

src/python_modern_template/api_client.py (75% coverage)

Covered:

  • Basic API calls
  • Authentication
  • Response parsing

Not Covered:

  • Retry logic (lines 112-118)
  • Connection error handling
  • Backoff mechanism

Missing Test Types:

  • Integration tests with retries
  • Failure scenario tests

Next Steps

Immediate Actions (30 minutes)

  1. Add error handling tests to validators.py

    # Edit tests/test_validators.py
    # Add test_validate_email_value_error_handling()
    # Add test_validate_email_unexpected_error_handling()
  2. Add edge case tests to parser.py

    # Edit tests/test_parser.py
    # Add test_parse_config_empty_data()
    # Add test_parse_config_none_data()
  3. Add integration tests to api_client.py

    # Edit tests/test_api_client.py
    # Add test_retry_with_backoff()
  4. Run coverage again

    make coverage

Expected Result: 83.5% coverage (exceeds 80% target!)

Verify Implementation

# Run tests to ensure they fail (TDD)
make test

# Verify uncovered code is exercised
# Fix any test issues
# Re-run coverage
make coverage

# Should see 80%+ coverage

Additional Recommendations

Use Parametrized Tests

For multiple similar test cases:

@pytest.mark.parametrize("email,valid", [
    ("test@example.com", True),
    ("invalid-email", False),
    ("", False),
    (None, False),
    ("test@", False),
    ("@example.com", False),
])
def test_validate_email_parametrized(email: str | None, valid: bool) -> None:
    """Test email validation with various inputs."""
    if valid:
        assert validate_email(email) is True
    else:
        assert validate_email(email) is False

Use Fixtures for Common Setup

@pytest.fixture
def sample_config():
    """Provide sample configuration for tests."""
    return {
        "api_url": "https://api.example.com",
        "timeout": 30,
        "retries": 3,
    }

def test_parse_config_with_defaults(sample_config):
    """Test config parsing with defaults."""
    result = parse_config(sample_config)
    assert result["timeout"] == 30

Focus on Critical Paths

Priority order:

  1. Error handling (catch exceptions)
  2. Edge cases (empty, None, invalid)
  3. Security checks (validation, authorization)
  4. Integration points (API calls, database)
  5. Business logic
  6. Utility functions

Coverage Best Practices

  1. Write tests FIRST (TDD) - Coverage comes naturally
  2. Test behavior, not implementation - Focus on what, not how
  3. Use real code over mocks - Only mock external dependencies
  4. Aim for 100% of new code - Don't lower the bar
  5. Track trends - Ensure coverage doesn't regress
  6. Review uncovered code regularly - Don't let gaps accumulate

Integration with Quality Tools

With make check

# Coverage is part of quality gates
make check

# Must pass 80%+ coverage requirement

With TDD Reviewer

# TDD reviewer checks coverage compliance
[tdd-reviewer]

# Includes coverage verification

With Coverage Command

# Generate HTML report
make coverage

# View in browser
open htmlcov/index.html

Remember

"Coverage percentage is a measure, not a goal." "Aim for meaningful tests, not just high numbers."

Good coverage means:

  • ✅ Critical paths tested
  • ✅ Error handling verified
  • ✅ Edge cases covered
  • ✅ Integration points tested

Bad coverage means:

  • ❌ Tests just to hit lines
  • ❌ Meaningless assertions
  • ❌ Over-mocking everything
  • ❌ Ignoring critical gaps

Focus on quality coverage, not just quantity!


## Advanced Features

### Historical Tracking

Store coverage data over time:

```bash
# Save current coverage
echo "$(date +%Y-%m-%d),$(coverage report | grep TOTAL | awk '{print $4}')" >> .coverage_history

# View trend
cat .coverage_history

Per-Module Breakdown

Analyze each module separately:

# Get coverage for specific module
coverage report --include="src/python_modern_template/validators.py"

Branch Coverage

Not just line coverage, but branch coverage:

# Enable branch coverage in pyproject.toml
[tool.pytest.ini_options]
branch = true

# Shows uncovered branches (if/else not both tested)

Diff Coverage

Focus on changed lines only:

# Install diff-cover
pip install diff-cover

# Check coverage of git diff
diff-cover htmlcov/coverage.xml --compare-branch=main

Remember

Coverage analysis is a tool for improvement, not a report card. Use it to:

  • Find gaps in testing
  • Prioritize test writing
  • Track progress
  • Ensure quality

But always remember: 100% coverage ≠ bug-free code. Write meaningful tests!