環境
pyproject.toml
requires-python = ">=3.13"
dependencies = [
"pytest>=8.3.4",
"pytest-cov>=6.0.0",
]
pytest-covでテストファイルがカバレッジ追跡対象にされてしまう
pytest-covは、pytestでカバレッジを出力するツールです。
pytestは*_test.py
かtest_*.py
というファイル名をテストとして扱います。pytest-covをインストールしてそのままカバレッジを表示すると、この*_test.py
かtest_*.py
というファイルをテスト対象として扱われてしまいます。
$ pytest --cov
---------- coverage: platform linux, python 3.13.1-final-0 -----------
Name Stmts Miss Cover
-----------------------------------
hello.py 14 7 50%
hello_test.py 3 0 100%
test_hello.py 3 0 100%
-----------------------------------
TOTAL 20 7 65%
omitを追加
pytest-covの設定でomitしておくと、カバレッジ計算の算出対象からテストファイルを除外できます。
pyproject.toml(追記)
[tool.coverage.run]
omit = [
"test/*",
"*/*_test.py",
"*/test_*.py",
]
---------- coverage: platform linux, python 3.13.1-final-0 -----------
Name Stmts Miss Cover
------------------------------
hello.py 14 7 50%
------------------------------
TOTAL 14 7 50%