Pythonパッケージのテストスイートのコードカバレッジ#
コードカバレッジは、テスト中にパッケージのコードがどれだけ実行されるかを測定します。 高いカバレッジを達成することは、コードベースの信頼性を確保するのに役立ちますが、品質を保証するものではありません。 以下に、コードカバレッジを効果的に使用するための主な検討事項を概説します。
なぜ高いコードカバレッジを目指すのか?#
良い習慣は、テストスイートの間に、コードのすべての行が少なくとも一度は実行されるようにすることです。これはあなたを助けます:
Identify untested parts: Parts of your codebase that are not covered by tests.
Catch bugs: Bugs that might otherwise go unnoticed.
Build confidence: Confidence in your software's stability.
コードカバレッジの限界#
高いコードカバレッジは価値がありますが、それには限界があります:
テストしにくいコード: コードの中には、複雑さや限られたリソースのために、テストが難しい部分があるかもしれません。
Missed edge cases: Running all lines of code doesn't guarantee that edge cases are handled correctly.
最終的には、パッケージがどのように使用されるかに焦点を当て、テストがそのシナリオを十分にカバーするようにしなければなりません。
Pythonパッケージのコードカバレッジを分析するツール#
Some common services for analyzing code coverage are codecov.io and coveralls.io. These projects are free for open source tools and provide dashboards that show how much of your codebase is covered during your tests. We recommend setting up an account (on either CodeCov or Coveralls) and using it to keep track of your code coverage.
The CodeCov platform is a useful tool if you wish to track code coverage visually. Using it, you can get the same summary information that you can get with the pytest-cov extension. You can also see what lines are covered by your tests and which are not. Code coverage is useful for evaluating unit tests and/or how much of your package code is "covered". It, however, will not evaluate things like integration tests and end-to-end workflows.#
型 & MyPyのカバレッジ
また、型レポートを作成し、CodeCovにアップロードすることもできます。
ローカルカバレッジレポートのエクスポート#
CodeCovやCoverallsのようなサービスを利用するだけでなく、 coverage.py ツールを使って直接ローカルカバレッジレポートを作成することもできます。 これは、オフラインでの使用や文書化のためにMarkdownやHTML形式でレポートを作成したい場合に特に便利です。
カバレッジレポートを Markdown 形式で作成するには、以下を実行します:
python -m coverage report --format=markdown
This command will produce a Markdown-formatted coverage summary that you can include in project documentation or share with your team.
どの行がカバーされているか、詳細でインタラクティブなビューを提供するHTMLレポートを生成するには、以下を使用します:
python -m coverage html
The generated HTML report will be saved in a directory named htmlcov by
default. Open the index.html file in your browser to explore your coverage
results.
このようなローカルレポートは、外部サービスを立ち上げることなくカバレッジを素早く確認する優れた方法です。
Next steps#
Writing meaningful tests is the foundation of useful coverage. See Write tests and Test types to learn more about developing better test suites. Learn how to run your tests both locally and in continuous integration.