建置並測試工具

使用 Claude Code 進行軟體開發

Dani Zysman

AI Curriculum Manager @ DataCamp

從規劃到程式碼

recraft: half: Developer at desk coding a CLI tool with terminal showing argparse output

  • 第 4.1 課的規格:
    • --artist — 要查詢的藝人名稱
    • --format — 輸出為 JSON 或 CSV
    • --output — 結果檔案路徑
  • Claude 會產生:
    • 使用 argparse 的引數解析
    • 透過 MCP 的資料庫查詢
    • 檔案輸出邏輯
使用 Claude Code 進行軟體開發

CLI 引數樣式

Pattern Example When to Use
Required --artist "AC/DC" 必填
Optional --format json 有合理預設
Flag --verbose 布林開關
Positional reporter.py data.csv 主要輸入
  • 最佳實務:
    • 為每個引數加入 --help 說明
    • 善用預設值以減少必填項
    • 及早驗證,失敗時清楚提示
使用 Claude Code 進行軟體開發

建置 Reporter

> 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, Verify Output

  • 測試驗證:
    • 合法藝人會回傳資料
    • 會建立輸出檔案
    • 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...