コンテンツにスキップ

GitHub Actions で pytest のカバレッジを出力する

MishaKav/pytest-coverage-commentの action を使うと、pytest で計測したカバレッジを GitHub の Pull Request や Job の Summary に出力できる。例は 2 通りある。

PR のコメントにカバレッジを出力する

次のワークフローは、mainブランチを指定した pytest-coverage-comment の action を使って、pytest を実行してカバレッジを計測し、結果を PR のコメントに出力する。

---
- name: Build coverage file
  run: |
    pytest --junitxml=pytest.xml --cov-report=term-missing:skip-covered --cov=app tests/ | tee pytest-coverage.txt

- name: Pytest coverage comment
  uses: MishaKav/pytest-coverage-comment@main
  with:
    pytest-xml-coverage-path: ./path-to-file/coverage.xml
    hide-comment: false

上のワークフローを実行した結果、PR には次のようなコメントが付いた。

Coverage

Coverage Report
FileStmtsMissCoverMissing
functions/example_completed
   example_completed.py641970%33, 39–45, 48–51, 55–58, 65–70, 91–92
functions/example_manager
   example_manager.py441175%31–33, 49–55, 67–69
   example_static.py40295%60–61
functions/my_exampels
   example.py20200%1–31
functions/resources
   resources.py26260%1–37
TOTAL105573930% 

Job の Summary にカバレッジを出力する

PR にコメントを残したくない場合は、hide-comment: trueを指定するとコメントを止められる。代わりにactions/github-scriptを使えば、カバレッジの結果を Job の Summary へ追記できる。

- name: Pytest coverage comment
  id: coverageComment
  uses: MishaKav/pytest-coverage-comment@main
  with:
    pytest-xml-coverage-path: ./path-to-file/coverage.xml
    hide-comment: true

- name: Add Summary
  uses: actions/github-script@v6
  with:
    script: |
      core.summary.addRaw(${{ steps.coverageComment.outputs.summaryReport }}).write()

参考