pytest代码覆盖率插件
一、官方文档
- coverage: https://coverage.readthedocs.io/en/7.2.1/
- pytest-cov:https://pypi.org/project/pytest-cov/
二、安装pytest插件(这个插件是依赖coverage.py,所以会自动安装coverage)
pip install pytest-cov
三、如何使用
# 指定目录,终端输入命令
pytest --cov=src

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

#生成报告,报告可以选择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
本文来自博客园,作者:弩哥++,转载请注明原文链接:https://www.cnblogs.com/bangbangzoutianya/p/17219882.html

浙公网安备 33010602011771号