LoginSignup
6
1

More than 1 year has passed since last update.

[GitHub Actions] 鬼の爆速実装!!!pytestのcoverageをPull Requestに表示させる

Last updated at Posted at 2022-11-17

この記事を読めばできるようになること

GitHub ActionsでpytestのcoverageをPRに表示させることができる

説明しないこと

  • GitHub Actionsとは何か
  • ymlファイルの記述方法

注意事項

これから紹介するソースはdockerを利用している

該当のyamlファイル

.github/workflows/coverage.yml
# タイミングを指定
on:
  pull_request:

permissions: write-all

jobs:
  pytest_coverage:
    runs-on: ubuntu-latest

    steps:
      # リポジトリをチェックアウト
      - name: Checkout
        uses: actions/checkout@v2

      - name: generate .env
        run: chmod +x set-up-env.action.sh && sh set-up-env.action.sh
        env:
          ENVIRONMENT_VARIABLE1: ${{ secrets.ENVIRONMENT_VARIABLE1 }}
          ENVIRONMENT_VARIABLE2: ${{ secrets.ENVIRONMENT_VARIABLE2 }}

      - name: Run Tests
        run: |
          docker-compose build
          docker-compose up -d
          docker-compose run app pytest --cov --cov-branch --cov-report=term-missing --junitxml=pytest.xml test | tee pytest-coverage.txt

      # テスト結果をプルリクにコメントする
      - name: Pytest coverage comment
        uses: MishaKav/pytest-coverage-comment@main
        with:
          pytest-coverage-path: ./pytest-coverage.txt
          junitxml-path: ./pytest.xml

コマンド説明

Run Testsコマンド

coverage.yml
 - name: Run Tests
   run: |
     docker-compose build
     docker-compose up -d
     docker-compose run app pytest --cov --cov-branch --cov-report=term-missing --junitxml=pytest.xml test | tee pytest-coverage.txt

docker-compose run app pytest --cov --cov-branch --cov-report=term-missing --junitxml=pytest.xml test | tee pytest-coverage.txtについて

  • docker-compose run appとすることでコンテナ内でコマンドを実行することが可能
  • --covでテスト結果のcoverageを表示させることが可能
  • --cov-branchで条件分岐の網羅テスト率(C1カバレッジ)を見ることが可能
  • --cov-report=term-missingでコマンドラインで網羅できなかったコード行番号を表示させることが可能
  • --junitxml=pytest.xmlでXUnit形式のテストレポートを指定したファイルに出力可能
  • tee pytest-coverage.txtで標準入力から受け取った内容をファイルに書き出すことが可能
  • 結果的にpytest.xmlcoverage.txtが新たに追加される

Pytest coverage comment

coverage.yml
 - name: Pytest coverage comment
   uses: MishaKav/pytest-coverage-comment@main
   with:
     pytest-coverage-path: ./pytest-coverage.txt
     junitxml-path: ./pytest.xml
  • pytest-coverage-commentよりそのまま引用
  • このアクションを GitHub のワークフローに追加すると、Ubuntu 用のランナー (runs-on: ubuntu-latest など) が作成できる
  • うまく行けば↓PRにこのように表示される
スクリーンショット 2022-10-24 9.28.58.png (91.7 kB)

Badge Colors

カバレッジ率によってバッジの色も変化する
スクリーンショット 2022-10-24 9.30.09.png (28.9 kB)

参考にさせていただきました

この記事がどなたかの手助けになっていれば幸いです。
6
1
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
6
1