-
Notifications
You must be signed in to change notification settings - Fork 3
Open
Labels
Description
使用 PyCharm 查看测试代码覆盖率
PyCharm 专业版本提供了测试同时输出代码覆盖率的运行选项。
使用结果如下图所示:

也可以在左边项目目录看到各目录及文件的覆盖率。
使用 pytest-cov
命令行下使用 pytest-cov
在命令行下使用 pytest-cov 的话还需要对项目进行一些设置。
参考 pytest-django:Managing Python Path 的文档
否则会报下面的错误:
ImportError: No module named 'wepost'
pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up.
这是因为本项目没有 manage.py 而是针对不同环境有多个. 所以 pytest-django 自动配置项目目录失败。所以需要手动配置一上。手动配置也比较简单。
- 添加一个简单的
setup.py脚本
import setuptools
setuptools.setup(name='wepost', version='1.0')- 执行
pip install -e .将当前项目作为一个本地开发包来对待,这样相当于加入了pythonpathpytest-django运行时便能导入wepost了。
然后执行针对 posts 目录的覆盖率测试如下:
➜ WePost (master) ✗ py.test --cov=wepost/apps/posts wepost/apps/posts/tests
====================================================================== test session starts ======================================================================
platform darwin -- Python 3.7.2, pytest-4.2.1, py-1.7.0, pluggy-0.8.1
Django settings: wepost.conf.test (from ini file)
rootdir: /Users/banxi/Workspace/WePost, inifile: tox.ini
plugins: django-3.4.7, cov-2.6.1
collected 1 item
wepost/apps/posts/tests/test_user_node_service.py . [100%]
---------- coverage: platform darwin, python 3.7.2-final-0 -----------
Name Stmts Miss Cover
-----------------------------------------------------------------------------
wepost/apps/posts/__init__.py 0 0 100%
wepost/apps/posts/admin.py 6 0 100%
wepost/apps/posts/apps.py 5 0 100%
wepost/apps/posts/enums.py 15 0 100%
wepost/apps/posts/migrations/0001_initial.py 7 0 100%
wepost/apps/posts/migrations/0002_init_nodes.py 51 45 12%
wepost/apps/posts/migrations/0003_auto_20190221_1604.py 9 0 100%
wepost/apps/posts/migrations/__init__.py 0 0 100%
wepost/apps/posts/models.py 65 3 95%
wepost/apps/posts/services.py 26 0 100%
wepost/apps/posts/tests/__init__.py 1 0 100%
wepost/apps/posts/tests/test_user_node_service.py 23 0 100%
wepost/apps/posts/views.py 1 1 0%
-----------------------------------------------------------------------------
TOTAL 209 49 77%
Reactions are currently unavailable