【问题标题】:Python SonarQube Integration with nosetests and coverage not shown cover codePython SonarQube 与鼻子测试和覆盖率的集成未显示封面代码
【发布时间】:2018-07-22 08:10:01
【问题描述】:

我创建了示例项目 (PyCharm+Mac) 以使用鼻子测试和覆盖率将 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]))

test/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 中的实际功能代码未显示在我的项目中,如下所示?

【问题讨论】:

  • 因为您只是在测试fact,这不是该文件中的代码的 100%?为什么你认为你会得到更多?
  • 当我检查 coverage.xml 时,它会显示事实代码的命中。

标签: python sonarqube code-coverage nose


【解决方案1】:

您应该始终尝试使一项测试失败,以确保您的命令测试了某些东西。以下命令不执行任何测试:

nosetests --with-coverage --cover-package=src --cover-inclusive --cover-xml

一种解决方案是在末尾添加test/*Test.py。 要只用一个命令生成nosetests.xmlcoverage.xml,可以执行:

nosetests --with-xunit --with-coverage --cover-package=src --cover-inclusive --cover-xml test/*Test.py

注意:你需要创建一个test/__init__.py文件(即使是空的),这样nosetests.xml中的文件路径才能解析出来。

注意:解析coverage.xml至少需要SonarPython 1.9版

【讨论】:

  • 我已经按照你的建议尝试了,它现在将覆盖 70% 但是当更改我的 *Test.py 文件并再次运行命令以检查覆盖率时,它将显示 70% 不会根据我的更改覆盖率百分比测试用例。
  • 我遇到了同样的问题:所以需要 1.9 版本才能在 sonar(python) 中显示单元测试覆盖率?
猜你喜欢
  • 2018-01-11
  • 2018-10-18
  • 2016-04-08
  • 2020-02-25
  • 2014-12-15
  • 2019-07-07
  • 1970-01-01
  • 2020-08-13
  • 2017-10-24
相关资源
最近更新 更多