🛠
Pythonのテスト環境の構築(pytest)
概要
- Pythonにpytestを導入する手順を説明します
- pytestのみではカバレッジの計測やwatchモードでの実行ができないため、それらの導入手順もあわせて説明します
バージョン情報
- Python: 3.10.7
- pytest: 7.1.3
- pytest-cov: 4.0.0
- pytest-watch: 4.2.0
各ライブラリの公式サイト
サンプルコード
サンプルコードはこちらです。
導入手順
pytestの導入
インストール
$ pip install pytest
テスト実行
テスト対象のコードは以下になります。
sample.py
def add(x, y):
return x + y
テストコードは以下になります。
test_sample.py
def test_add():
assert add(1, 2) == 3
テストを実行します
$ pytest test_sample.py
例外のテスト
例外を発生させるコードのテストはpytest.raisesを使用します
sample.py
def raise_zero_division_error():
return 1 / 0
test_sample.py
def test_raise_zero_division_error():
with pytest.raises(ZeroDivisionError):
raise_zero_division_error()
parameterizeを使用したテスト
入力値のバリエーションをテストしたい場合はpytest.parameterizeを使用します
test_sample.py
def test_add():
assert add(1, 2) == 3
test_sample.py
@pytest.mark.parametrize(
"input,expected",
[({"x": 1, "y": 2}, 3), ({"x": 10, "y": 5}, 15)]
)
def test_add(input, expected):
assert add(input["x"], input["y"]) == expected
カバレッジの計測
pytestのみではカバレッジを計測できないため、別途pytest-covをインストールする必要があります。
pytest-covのインストール
$ pip install pytest-cov
pytestの実行時のオプションに--covを追加することで命令網羅(C0)のカバレッジを計測できす。
$ pytest --cov=sample
---------- coverage: platform darwin, python 3.7.8-final-0 -----------
Name Stmts Miss Cover
-------------------------------
sample.py 9 0 100%
-------------------------------
TOTAL 9 0 100%
条件網羅(C1)のカバレッジを計測する場合は--cov-branchを追加します。
$ pytest --cov=sample --cov-branch test_sample.py
test_sample.py ..... [100%]
---------- coverage: platform darwin, python 3.7.8-final-0 -----------
Name Stmts Miss Branch BrPart Cover
---------------------------------------------
sample.py 9 0 2 0 100%
---------------------------------------------
TOTAL 9 0 2 0 100%
watchモードでのテスト
ここまででpytestの導入方法を説明しました。
ただしこのままではコードを修正するたびに毎回pytestコマンドの実行が必要になります。
pytest-watchを使用することで、pytestをwatchモードで実行しコードの変更を検知して自動で再テストします。
pytest-watchのインストール
$ pip install pytest-watch
watchモードでの実行
$ pytest-watch # or ptw
これでソースコードを修正するたびに自動で再テストが実行されます。
pytestのオプションをつけてwatchモードで実行したい場合はpytest-watchをrunnerオプション付きで実行します
$ pytest-watch --runner "python -m pytest --cov=sample test_sample.py"
Discussion