我创建了示例项目(PyCharm+Mac),使用 Nose 测试和覆盖率将 SonarQube 集成到 python 中:
src/Sample.py
import sys
def fact(n):
"""
Factorial function
:arg n: Number
:returns: factorial of n
"""
if n == 0:
return 1
return n * fact(n - 1)
def main(n):
res = fact(n)
print(res)
if __name__ == '__main__' and len(sys.argv) > 1:
main(int(sys.argv[1]))
测试/SampleTest.py
import unittest
from src.Sample import fact
class TestFactorial(unittest.TestCase):
"""
Our basic test class
"""
def test_fact1(self):
"""
The actual test.
Any method which starts with ``test_`` will considered as a test case.
"""
res = fact(0)
self.assertEqual(res, 1)
def test_fac2(self):
"""
The actual test.
Any method which starts with ``test_`` will considered as a test case.
"""
res = fact(5)
self.assertEqual(res, 120)
if __name__ == '__main__':
unittest.main()
Sonar 项目.properties
sonar.projectKey=SonarQubeSample
sonar.projectName=Sonar Qube Sample
sonar.projectVersion=1.0
sonar.sources=src
sonar.tests=test
sonar.language=py
sonar.sourceEncoding=UTF-8
sonar.python.xunit.reportPath=nosetests.xml
sonar.python.coverage.reportPath=coverage.xml
sonar.python.coveragePlugin=cobertura
以下命令将成功创建nosetests.xml文件:
nosetests --with-xunit ./test/SampleTest.py
当我运行以下命令时:
nosetests --with-coverage --cover-package=src --cover-inclusive --cover-xml
它将给出以下结果:
Name Stmts Miss Cover
-------------------------------------
src/Sample.py 10 6 40%
src/__init__.py 0 0 100%
-------------------------------------
TOTAL 10 6 40%
----------------------------------------------------------------------
Ran 0 tests in 0.011s
OK
为什么在运行 sonar-scanner
命令后,事实功能代码未显示覆盖到 SonarQube 我的项目中,如下所示?
最佳答案
您应该始终尝试使一个测试失败,以确保您的命令测试了某些内容。以下命令不执行任何测试:
nosetests --with-coverage --cover-package=src --cover-inclusive --cover-xml
一种解决方案是在末尾添加 test/*Test.py
。
要仅使用一个命令生成 nosetests.xml
和 coverage.xml
,您可以执行:
nosetests --with-xunit --with-coverage --cover-package=src --cover-inclusive --cover-xml test/*Test.py
注意:你需要创建一个test/__init__.py
文件(甚至是空的),这样才能解析nosetests.xml
中的文件路径。
注意:您至少需要 SonarPython 1.9 版本才能解析 coverage.xml
关于Python SonarQube 与 Nose 测试和覆盖率集成未显示覆盖代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741685/