LoginSignup
4
1

More than 1 year has passed since last update.

unittestとpytestでそれぞれC1カバレッジ出力のコマンドを最小限に抑えてみました。

Last updated at Posted at 2021-03-28

Pythonでテストしてカバレッジを取得する時にあれこれコマンドが長くなるなぁと思いつつ特に気にせず作業していたんですけど、やっぱり長いのを打つのってけっこうめんどくさい。。ということで、テストコマンドを最小限に抑えるための設定ファイルの作り方を探った時のメモ的なものです。

2021年3月時点で最新のunittestとpytestに対応しています。今回はテストのコマンドを短くすることに目的をおいているので、テストコードの例は省いています。

環境

  • Windows10
  • Python3.9インストール済

今回のディレクトリ構成

proj_unittest/
  ├ src/
  │   ├ app/
  │   │   ├ __init__.py
  │   │   └ main.py
  │   ├ tests/
  │   │   ├ __init__.py
  │   │   └ test_app_main.py
  │   └ __init__.py
  └ .coveragerc

proj_pytest/
  ├ src/
  │   ├ app/
  │   │   ├ __init__.py
  │   │   └ main.py
  │   ├ tests/
  │   │   ├ __init__.py
  │   │   └ test_app_main.py
  │   └ __init__.py
  └ pytest.ini

unittestの場合

準備

.coveragercを準備します。

今回はC1カバレッジ(判定条件網羅)を出力するためにbranch = trueを書いています。テストコードでカバーできてない行をコマンド出力するためにshow_missing = trueも追加しています。

proj_unittest/.coveragerc
[run]
source = src/app
branch = true
command_line = -m unittest

[report]
show_missing = true

coverageをインストールします。

$ pip install coverage

テスト&カバレッジ出力

[Before]

$ coverage run --source=src/app --branch -m unittest  ← テスト
$ coverage report -m                                  ← コマンド出力
$ coverage html                                       ← HTML出力

[after]

$ coverage run
$ coverage report
$ coverage html

だいぶきれいになりました。

pytestの場合

準備

pytest.iniを準備します。

C1カバレッジを出力するために--cov-branchを書いています。テストコードでカバーできてない行をコマンド出力するために--cov-report=term-missing、自動でHTMLを出力する機能もあるので--cov-report=htmlも追加しています。

proj_pytest/pytest.ini
[pytest]
addopts=
  --cov=src/app
  --cov-branch
  --cov-report=term-missing
  --cov-report=html

pytestpytest-covをインストールします。

$ pip install pytest pytest-cov

テスト&カバレッジ出力

[before]

$ pytest --cov=src/app --cov-branch --cov-report=term-missing --cov-report=html

[after]

$ pytest

pytestの場合はこれでカバレッジ出力も自動でやってくれるからほんと便利です。

参考

4
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
4
1