0
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?

CI/CD入門②pytest

Posted at

はじめに

CI/CDを実装し始めたイカだイカ🦑
前回まで、CI/CDでインデントやimportの順番、自動改行を実装したイカ🦑
今回はテストを自動化する、pytestの実装を行っていくイカ🦑

使用する技術スタック

fastapi
uvicorn
sqlalchemy
python-dotenv
google-genai
chromadb
langchain
langchain-community
langchain-google-genai
sentence-transformers
pydantic==2.5.0
pre-commit
black
isort
pytest
httpx

手順

  1. pytestをインストール
  2. ルートディレクトリにtests/test_main.pyを作成
  3. 作成したtest_main.pyに下記のように実装をする。今回はユーザー登録APIのテストを行っていく
# tests/test_main.py

from fastapi.testclient import TestClient
from app.main import app # 💡 テスト対象のFastAPIアプリ本体をインポート

# TestClientを作成
# これを使うと、Uvicornを起動しなくても、アプリにHTTPリクエストを送れます
client = TestClient(app)

# --------------------------
# ユーザー登録APIのテスト
# --------------------------
def test_create_user_success():
    """
    ユーザー登録が成功するケースをテスト
    """
    # 🚨 注意: このテストを実行する前に、
    # main.pyでインデックス化処理が走るとデータベースが初期化されるため、
    # 実際のテスト環境ではDBをモック化するか、テスト専用DBを使います。
    # 今回はシンプルに、エンドポイントが200 OKを返すことだけを確認します。
    
    response = client.post(
        "/user/create_user",
        json={"password": "testpassword"},
    )
    
    # HTTPステータスコードが200 OKであることを確認 (成功の検証)
    assert response.status_code == 200
    
    # 返されたJSONデータに'id'が含まれていることを確認
    data = response.json()
    assert "id" in data
    assert data["password"] == "testpassword"

# --------------------------
# 存在しないエンドポイントのテスト
# --------------------------
def test_read_non_existent_route():
    """
    存在しないパスにアクセスしたとき、404エラーになることをテスト
    """
    response = client.get("/non_existent_route")
    
    # HTTPステータスコードが404 Not Foundであることを確認 (失敗の検証)
    assert response.status_code == 404
  1. ターミナルで下記を実行
pytest

実行が成功したら、以下のような結果が表示される。

============================= test session starts ==============================
platform darwin -- Python 3.11.7, pytest-7.4.3, pluggy-1.3.0
rootdir: /path/to/your/project
collected 2 items

tests/test_main.py ..                                                    [100%]

============================== 2 passed in 0.XXs ===============================
  1. ターミナルにpytestと手動で成功するようになったら、これをCIの処理を記述しているファイルから実行できるようにする
    1. 前回作成した.pre-commit-config.yamlファイルに下記のように追記する
# ... 既存の black, isort, end-of-file-fixer の設定の下に追記 ...

  # 4. pytest (テスト実行)
  - repo: local
    hooks:
      # id はユニークであれば何でもOK
      - id: pytest
        name: Run pytest (Unit/Integration Tests)
        entry: pytest # 実行するコマンド
        language: system # システムにインストールされているpytestを使用
        types: [python]
        # files: 
        #   FastAPIのコード(.py)や依存ファイル(e.g., .env, .yaml)が変更されたら実行
        #   一旦は常に実行する設定にしておきます。

これで前回行った通り、
git addをして、コミットをする。
コミット実行後にpytestまで完了したらプッシュが自動で行われる。

おわりに

ここまでpytestをCIで自動化する処理について書いてきたイカ🦑
プッシュ事にテストが行われるなんてとっても素敵イカね🦑

0
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
0
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?