1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Djangoでテストのカバレッジを取得する

Posted at

弊社で開発しているDjangoアプリケーションのテストのカバレッジを取得したくなったので、Coverage.pyを利用してカバレッジを取得します。

まずはCoverage.pyをpipenvでインストールします。

$ pipenv install -d coverage

インストールできたら、pipenv shellで仮想環境を起動し、以下のコマンドでプロジェクト全体でテストを実行します。テストが完了すると、簡易的にテストを結果を表示します。

$ coverage run --source='.' manage.py test
Creating test database for alias 'default'...
Ran 40 tests in 7.188s

OK

以下のコマンドでカバレッジを表示できます。

$ coverage report
Name                                                    Stmts   Miss  Cover
---------------------------------------------------------------------------
config/settings.py                                         48      0   100%
config/urls.py                                              7      0   100%
config/wsgi.py                                              4      4     0%
core/admin.py                                             216     15    93%
core/api.py                                              1240    840    32%
core/apps.py                                                3      3     0%
core/helpers.py                                            89     72    19%
core/models.py                                           1079    290    73%
core/serializers.py                                       227      3    99%
core/urls.py                                               43      0   100%
core/views.py                                             156    116    26%
core/visualize.py                                         267    267     0%
・・・(以下略)・・・
---------------------------------------------------------------------------
TOTAL                                                   11170   8081    28%

カバレッジを取得する範囲をコマンドのオプションで指定することができますが、コマンドを実行するたびに指定するのが面倒くさいので、.coveragercを定義して、コマンドのオプションを省略できるようにします。

.coveragerc
[run]
omit =
    */tests/*
    */migrations/*
    */__init__.py
    .venv/*


[report]
omit =
    */tests/*
    */migrations/*
    */__init__.py
    .venv/*


[html]
directory = cover

最後に以下のコマンドで上記のカバレッジをHTMLファイルとして出力することもできます。

$ coverage html

## テストの実行からHTMLファイルの出力までワンライナー実行
$ coverage run --source='.' manage.py test && coverage report && coverage html
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?