pytest代码覆盖率插件

一、官方文档

二、安装pytest插件(这个插件是依赖coverage.py,所以会自动安装coverage)

pip install pytest-cov

三、如何使用

# 指定目录,终端输入命令
pytest --cov=src 

image

# 指定目录下的指定文件(模块)
# 根据上图可以看出来,我的src目录下,有2个文件(模块),一个是calc.py,
pytest --cov=src.calc

image

#生成报告,报告可以选择html格式
# cov-report html:cov 生成html格式 cov是生成的目录
pytest --cov=src --cov-report html:cov

四、示例代码

calc.py

class Calc:
    @staticmethod
    def add(a, b):
        return a + b

    @staticmethod
    def sub(a, b):
        return a - b

    @staticmethod
    def div(a, b):
        if b == 0:
            raise Exception("除数不能为0")
        return a/b

calc_test.py

from src.calc import Calc
import pytest


class TestCalc:
    c = Calc()

    @pytest.mark.parametrize("num1,num2,expect", [[1, 2, 3], [2, 3, 5]])
    def test_add(self, num1, num2, expect):
        assert self.c.add(num1, num2) == expect

    @pytest.mark.parametrize("num1,num2,expect", [[1, 2, -1], [10, 3, 7]])
    def test_sub(self, num1, num2, expect):
        assert self.c.sub(num1, num2) == expect

    @pytest.mark.parametrize("num1,num2,expect", [[10, 5, 2], [20, 4, 5]])
    def test_div(self, num1, num2, expect):
        assert self.c.div(num1, num2) == expect
posted @ 2023-03-15 20:57  弩哥++  阅读(229)  评论(0)    收藏  举报