如何在 PyCharm for Python 项目中获取代码覆盖率报告

如何在 PyCharm for Python 项目中获取代码覆盖率报告

问题描述:

我在 python 中创建了一个简单的加法方法,例如[main.py]

I have created a simple addition method in python like [main.py]

class Calculator:

    def sum(self,a,b):
        return a+b

我已经在 [test.py] 中编写了测试用例

And I have written test case in [test.py]

from unittest import Testcase
from main import Calculator

class TestCalculator(TestCase):

    def setUp(self):
        self.calc=Calculator()

    def test_sum(self):
        answer=self.cals.sum(2,4)
        self.assertEqual(answer,6)

现在我想检查这段代码的代码覆盖率.我不知道如何在 PyCharm IDE 中获取覆盖率报告.任何人,如果您知道如何获得整个项目的代码覆盖率,请指导

Now I want to check code coverage of this code. I am not getting how to get the coverage report in PyCharm IDE. Anyone, please guide if you know how to get the code coverage of the whole project

你可以使用 Coverage.py.只需 pip install coverage 并在 test.py 或 main.py 上添加一个 main 方法并运行它.

You could just use Coverage.py. Just pip install coverage and add a main method on your test.py or main.py and run it.

例如添加到test.py,

For example, add to test.py,

if __name__ == '__main__':
    unittest.main()

并在终端上运行,

coverage test.py