代码覆盖

代码覆盖是查找未被测试执行的代码区域的过程。不过要记住的是这并不能说明你测试代码的有效性。

requirements.txt文件中添加依赖包:

coverage==4.4.2

然后,我们在manage.py中新增一个命令:

import coverage
COV = coverage.coverage(
    branch=True,
    include='project/*',
    omit=[
        'project/tests/*'
    ]
)
COV.start()

@manager.command
def cov():
    """Runs the unit tests with coverage."""
    tests = unittest.TestLoader().discover('project/tests')
    result = unittest.TextTestRunner(verbosity=2).run(tests)
    if result.wasSuccessful():
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        COV.html_report()
        COV.erase()
        return 0
    return 1

因为新增了依赖包,所以需要重新构建容器:

(tdd3)$ docker-compose -f docker-compose.yml up -d --build

构建完成后执行代码覆盖命令:

(tdd3)$ docker-compose -f docker-compose.yml run users-service python manage.py cov

然后你能看到测试下面的信息:

Coverage Summary:
Name                    Stmts   Miss Branch BrPart  Cover
---------------------------------------------------------
project/__init__.py        12      5      0      0    58%
project/api/models.py      13     10      0      0    23%
project/api/views.py       55      0     10      0   100%
project/config.py          16      0      0      0   100%
---------------------------------------------------------
TOTAL                      96     15     10      0    86%

然后我们可以看到项目根目录中多了一个htmlcov的文件夹,该目录下面是自动生成的代码覆盖的结果页面,我们可以在浏览器中打开htmlcov/index.html,可以看到一个页面: code-cv-result 另外要记得将htmlcov文件夹添加到.gitignore文件中~