我创建了示例项目(PyCharm + Mac),使用nosetests和coverage将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-project.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我的项目中?
答案 0 :(得分:1)
您应该始终尝试使一个测试无法确定您的命令测试某些内容。以下命令不执行任何测试:
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