ツールの構築とテスト

Claude Code によるソフトウェア開発

Dani Zysman

AI Curriculum Manager @ DataCamp

計画からコードへ

recraft: half: 机でCLIツールのコードを書く開発者、ターミナルにargparseの出力を表示

  • レッスン4.1の仕様:
    • --artist — 検索するアーティスト名
    • --format — JSONまたはCSV形式の出力
    • --output — 結果の出力先ファイルパス
  • Claudeが生成する内容:
    • argparseによる引数解析
    • MCP経由のデータベースクエリ
    • ファイル出力ロジック
Claude Code によるソフトウェア開発

CLI引数のパターン

パターン 例 使用場面
必須 --artist "AC/DC" 必ず指定する必要がある
オプション --format json 適切なデフォルト値がある
フラグ --verbose 真偽値のオン/オフ
位置引数 reporter.py data.csv 主要な入力
  • 推奨される手法:
    • すべての引数に--helpの説明を追加する
    • デフォルト値を使い、必須入力を減らす
    • 早めに検証し、分かりやすいメッセージで即座に失敗させる
Claude Code によるソフトウェア開発

レポーターの構築

> Use @PLAN.md to build reporter.py
Done! Created reporter.py following PLAN.md

Core functions:
- get_db_connection()     Read-only SQLite with validation
- fetch_artist_stats()    4 SQL queries for aggregates
- format_json/csv()       Output formatting
- write_output()          File writing
- parse_args() / main()   CLI orchestration

Features:
- Case-insensitive artist lookup
- Per-album breakdown with revenue
- All error messages as specified
- --db flag for test injection
Claude Code によるソフトウェア開発

生成されたコード

import argparse, sqlite3, json, csv

def main():
    parser = argparse.ArgumentParser()
    ...
    args = parser.parse_args()

    conn = sqlite3.connect("chinook.db")
    # Query artist's albums and tracks...

    if args.format == "json":
        with open(args.output, "w") as f:
            json.dump(data, f, indent=2)
Claude Code によるソフトウェア開発

ツールをテストする

flowchart: reporter.py、pytest、出力を検証

  • テストで確認する内容:
    • 有効なアーティストでデータが返される
    • 出力ファイルが作成される
    • JSON/CSV形式が正しい
Claude Code によるソフトウェア開発

CLIツールのテスト

  • ユニットテスト
    • 個々の関数をテスト
    • データベース呼び出しをモック化
    • 高速で独立しており再現性がある
  • 統合テスト
    • 実際のCLIコマンドを実行
    • 実データベースを使用
    • 速度は遅いが、より実環境に近い
  • テスト対象:
    • 正常系 — 有効なアーティスト、正しい出力
    • エラーケース — アーティストが見つからない、不正な形式
    • エッジケース — 空の名前、特殊文字
    • ファイル処理 — 書き込み権限、上書き
Claude Code によるソフトウェア開発

テストの実践

> Use @PLAN.md to build test_reporter.py
Created test_reporter.py: 31 tests across 7 classes

Coverage:
- Connection     Valid DB, missing file, invalid file
- Stats          Known/unknown artist, case-insensitive, multi-genre
- JSON           Format, indentation, round-trip serialization
- CSV            Two sections, pipe-delimited genres, row counts
- File I/O       Write, overwrite, unwritable path
- CLI args       Required args, choices validation
- Integration    JSON/CSV output, artist/DB not found, cleanup

Uses minimal seeded SQLite DB: independent of chinook.db

All 31 tests passing!
Claude Code によるソフトウェア開発

練習しましょう!

Claude Code によるソフトウェア開発

Preparing Video For Download...