外部ファイル(CSVやJSON)にまとめたテストケースを CI/CDパイプラインに組み込む方法を、初心者向けに整理してみます。
全体の流れ
- テストケースを外部ファイルに保存(CSVやJSON)
- pytestなどで読み込むコードを書く(前回の例のように)
- CI/CD環境にテスト実行を組み込む(GitHub Actions, GitLab CI, Azure DevOps, CircleCIなど)
- テストが自動で走るように設定(pushやPR時に実行)
🛠️ 例:GitHub Actionsでの組み込み
1. プロジェクト構成例
project/
├── myapp.py
├── tests/
│ ├── test_app.py
│ ├── test_cases.json
│ └── test_cases.csv
└── .github/
└── workflows/
└── ci.yml
2. pytestコード(外部ファイル読み込み)
import json
import pytest
from myapp import can_access
def load_json_cases(filename="tests/test_cases.json"):
with open(filename) as f:
return json.load(f)
@pytest.mark.parametrize("case", load_json_cases())
def test_can_access(case):
assert can_access(case["age"], case["is_member"], case["has_invite_code"]) == case["expected"]
Python3. GitHub Actions設定 (.github/workflows/ci.yml)
name: CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest
- name: Run tests
run: pytest
ポイント
- 外部ファイルをリポジトリに含めることで、CI環境でも同じテストデータを利用可能
- pytestのパラメータ化でテストケースを一括管理
- CI/CDパイプラインに
pytest実行を組み込むと、pushやPR時に自動でテストが走る - 失敗したらビルドが止まるので、条件チェックの不備を早期に発見できる
実務的な工夫
- テストデータを別リポジトリや外部ストレージに置く → 大規模案件で便利
- 環境ごとに異なるテストデータを読み込む → 開発用・本番用で切り替え可能
- CI/CDでレポート出力(JUnit形式やHTML) → テスト結果を可視化


