1.首先我们编写一个简单的测试用例
from django.test import TestCase def division_funtion(x, y): return x / y class AnimalTestCase(TestCase): def setUp(self): pass def testCase1(self): print(1) def testCase2(self): division_funtion(1,2) def testCase3(self): division_funtion(1,3)
用python manage.py test启动它进行测试
结果大概是这样的
L:\test\HelloWorld>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). 1 ..E =========================================================== ERROR: testCase3 (HelloWorld.test.AnimalTestCase) ----------------------------------------------------------- Traceback (most recent call last): File "L:\test\HelloWorld\HelloWorld\test.py", line 21, in division_funtion(1,0) File "L:\test\HelloWorld\HelloWorld\test.py", line 6, in return x / y ZeroDivisionError: division by zero ----------------------------------------------------------- Ran 3 tests in 0.003s FAILED (errors=1) Destroying test database for alias 'default'... L:\test\HelloWorld>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). 1 ... ----------------------------------------------------------- Ran 3 tests in 0.002s OK Destroying test database for alias 'default'...
2.然后coverage上场。
首先是安装
pip install coverage
然后测试
coverage run manage.py test
于是乎我们会得到一个小报告
L:\test\HelloWorld>coverage run manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). 1 ... ------------------------------------------------- Ran 3 tests in 0.000s OK Destroying test database for alias 'default'...
如果想直接看到报告可以用report指令
L:\test\HelloWorld>coverage report Name Stmts Miss Cover -------------------------------------------- HelloWorld\__init__.py 0 0 100% HelloWorld\settings.py 18 0 100% HelloWorld\test.py 12 0 100% HelloWorld\urls.py 3 0 100% manage.py 9 2 78% -------------------------------------------- TOTAL 42 2 95%
我们还可以用html显示出来
L:\test\HelloWorld>coverage html
会在项目下面生成html文件
然后咱就打开来看看

点进文件还能看到每个文件的覆盖率

整合到sonar里面,可以用一个绝对路径试一下
sonar.python.coverage.reportPaths=/opt/test_proj/coverage-reports/coverage.xml
、
posted on
浙公网安备 33010602011771号