4

Pytest插件pytest-cov:优雅管理测试覆盖率

 8 months ago
source link: https://blog.51cto.com/summerstone/9191261
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Pytest插件pytest-cov:优雅管理测试覆盖率

精选 原创

SummerStone 2024-01-11 08:33:54 ©著作权

文章标签 测试覆盖率 Pytest Pytest插件 文章分类 软件测试 阅读数254

在软件开发中,测试覆盖率是评估测试质量的关键指标之一。为了更方便地统计和管理测试覆盖率,Pytest插件"pytest-cov"应运而生。本文将介绍"pytest-cov"的基本用法和优雅管理测试覆盖率的方法。

Pytest插件pytest-cov:优雅管理测试覆盖率_Pytest插件

什么是pytest-cov?

pytest-cov 是Pytest的一个插件,它提供了一种简单而强大的方式来测量和报告代码的测试覆盖率。通过集成测试覆盖率工具,pytest-cov可以帮助开发者了解哪些部分的代码被测试覆盖,哪些部分还需要进一步的测试。

Pytest插件pytest-cov:优雅管理测试覆盖率_测试覆盖率_02

安装pytest-cov

在开始之前,首先需要安装"pytest-cov"。使用以下命令:

pip install pytest pytest-cov

Pytest插件pytest-cov:优雅管理测试覆盖率_测试覆盖率_02

pytest-cov基本用法

本篇文章以下的篇幅将根据一个实际的案例来介绍pytest-cov的基本用法。

假设你有一个名为my_project 的项目,其中包含一个名为 calculator 的模块,你想要使用pytest-cov来测试并测量 calculator 模块的覆盖率。以下是一个简单的案例:

1. 项目结构

my_project/
   ├── calculator/
   │   ├── __init__.py
   │   └── calculator.py
   ├── tests/
   │   ├── __init__.py
   │   └── test_calculator.py
   └── pytest.ini

2. calculator.py代码内容:

# my_project/calculator/calculator.py




   def add(a, b):
       return a + b




   def subtract(a, b):
       return a - b

3. test_calculator.py代码内容:

# my_project/tests/test_calculator.py




   from calculator.calculator import add, subtract




   def test_add():
       result = add(3, 5)
       assert result == 8




   def test_subtract():
       result = subtract(10, 4)
       assert result == 6

4.  pytest.ini的设置内容:

# my_project/pytest.ini




   [pytest]
   addopts = --cov=calculator --cov-report=html

5. 运行测试:

在项目的根目录下运行以下命令: 

pytest tests/

此外如果想同时生成HTML格式的覆盖率报告,可以运行:

pytest --cov=calculator --cov-report=html tests/

这将运行 tests/ 目录下的测试,并使用pytest-cov测量 calculator 模块的覆盖率。HTML报告将生成在项目根目录下的 htmlcov 文件夹中。执行完之后,打开htmlcov文件夹,打开index.html,内容如下截图:

Pytest插件pytest-cov:优雅管理测试覆盖率_Pytest插件_04

如果更改测试文件的代码,比如删除一个测试函数 test_subtract 那么,此时覆盖率就不应该是100%了,有兴趣的话,大家可以试一试。

通过这个简单的案例,你可以了解如何使用pytest-cov来测试和测量项目中特定模块的代码覆盖率。在实际项目中,你可以根据项目结构和需要进行适当的调整。

在后续的文章中将继续深入讲解覆盖率相关的内容,如果大家觉得内容还可以,还请多多点赞,转发,谢谢。

如下是笔者在51CTO平台的软件自动化相关的视频教程,有兴趣的话,可以扫描查看。

Pytest插件pytest-cov:优雅管理测试覆盖率_Pytest_05

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK