1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GitHub Actions で FastAPI + PostgreSQL テストを自動実行する

Posted at

はじめに

FastAPI アプリの DB が絡むテストを自動化したく、GitHub Actions 上でテスト用 DB コンテナを立ち上げて pytest を実行する設定をまとめました。

前提

  • モノレポ構成
  • アプリとテスト DB は Docker コンテナでローカル開発済み
  • モックは使わず、実際の DB に対してテストを実行
  • Poetry で依存管理

CI でのテスト実行方法の候補

今回は以下を採用

アプリコンテナを使わず、GitHub Actions 上で直接 pytest を実行

アプリコンテナ + テスト DB コンテナを Docker Compose で起動

メリット

  • ローカル開発環境と同じ構成でテスト可能

デメリット

  • 実行時間が長い - イメージビルド + コンテナ起動時間
  • リソース消費大 - CPU/メモリ使用量が多い

アプリコンテナを使わず、GitHub Actions 上で直接 pytest を実行

メリット

  • Python 環境だけで完結する
  • CI ジョブが速くなる

デメリット

  • 環境差異リスク - 本番コンテナ環境との微妙な違いが生じる可能性

GitHub Actionsの設定

トリガー条件

 on:
    push:
      branches: [ main ]
      paths:
        - 'workspaces/issue-6/app/**'
        - '.github/workflows/test-issue-6-app.yml'
    pull_request:
      paths:
        - 'workspaces/issue-6/app/**'
        - '.github/workflows/test-issue-6-app.yml'

ポイント: モノレポ構成のため関連ファイル変更時のみ実行してCI時間とコストを節約

サービスコンテナ設定

services:
    postgres:
      image: postgres:15-alpine
      env:
        POSTGRES_DB: testdb
        POSTGRES_USER: testuser
        POSTGRES_PASSWORD: testpassword
      ports:
        - 5432:5432
      options: >-
        --health-cmd="pg_isready -U testuser -d testdb"
        --health-interval=10s
        --health-timeout=5s
        --health-retries=5

ソースコードのチェックアウト

- name: Checkout code
        uses: actions/checkout@v4

Python環境設定

- name: Set up Python
    uses: actions/setup-python@v5
    with:
      python-version: "3.11"

依存関係管理(Poetry)

- name: Install Poetry
    run: pip install poetry

- name: Install dependencies
    run: |
      cd workspaces/issue-6/app
      poetry lock
      poetry install --no-interaction --no-root

PYTHONパスの設定

env:
    PYTHONPATH: ${{ github.workspace }}/workspaces/issue-6/app

pytest実行


env:
    TEST_DATABASE_URL: postgresql://testuser:testpassword@localhost:5432/testdb
  run: |
    cd workspaces/issue-6/app
    poetry run pytest -v
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?