领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

使用pytest进行单元测试(pytest unittest)

nixiaole 2025-06-04 00:29:02 知识剖析 4 ℃

一、pytest 简介

pytest 是 Python 中最流行的单元测试框架,相比内置的 unittest 更简洁高效,支持自动发现测试用例、参数化测试、异常验证及丰富的插件生态。其核心优势包括:

  • 简洁语法:使用 assert 语句替代复杂的 TestCase 类
  • 自动发现:自动识别 test_*.py 或 *_test.py 文件中的测试用例
  • 扩展性强:支持 900+ 插件(如生成 HTML 报告、分布式测试等)

二、安装与验证

  1. 安装命令
pip install pytest  # 基础安装
pip install pytest-html  # 可选:生成 HTML 测试报告
  1. 验证安装:
pytest --version  # 显示版本号即成功
  1. 测试文件命名规则
    测试文件需以 test_*.py 或 *_test.py 命名,测试函数以 test_ 开头。

三、编写第一个测试用例

假设我们有一个加法函数 add(),编写测试用例:

# math_operations.py
def add(a, b):
    return a + b

# test_math_operations.py
from math_operations import add

def test_add():
    assert add(1, 2) == 3  # 基础测试
    assert add(-1, 1) == 0  # 边界测试
    assert add(0, 0) == 0  # 特殊值测试

运行测试

pytest  # 自动发现并执行测试

输出示例:

collected 1 item
test_math_operations.py .  [100%]

四、参数化测试

使用 @pytest.mark.parametrize 批量测试多组数据:

import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (-1, -1, -2),
    (100, 200, 300),
    ("a", "b", "ab")  # 类型测试
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

五、Fixtures(测试夹具)

用于测试前后的资源准备与清理:

# conftest.py  # 全局夹具文件
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

def test_sum(sample_data):
    assert sum(sample_data) == 6  # 使用夹具数据

作用域控制

  • function(默认):每个测试函数执行前后运行
  • class:每个测试类执行前后运行
  • module:每个模块执行前后运行

六、异常与标记

  1. 异常测试
def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("除零错误")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)  # 验证异常类型
  1. 测试标记
  2. 定义标记:在 pytest.ini 中配置
[pytest]
markers = smoke: 冒烟测试, serial: 串行执行
  1. 应用标记:
@pytest.mark.smoke
def test_feature():
    pass  # 只有标记为 smoke 的测试会被选中运行

七、持续集成集成

在 Jenkins 中配置 pytest:

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                sh 'pytest --junitxml=test-report.xml'  # 生成测试报告
            }
        }
    }
}

八、扩展工具

  • pytest-cov:生成代码覆盖率报告
  • pytest-xdist:支持多核并行测试加速
  • pytest-bdd:行为驱动开发(BDD)支持

九、最佳实践

  1. 命名规范 测试函数名:test_<功能描述>_<场景> 测试类名:Test<功能模块>
  2. 独立性
    每个测试用例应独立运行,避免共享状态。
  3. 分层设计
    推荐分层结构:
tests/
├── conftest.py  # 全局夹具
├── test_unit/    # 单元测试
└── test_integration/  # 集成测试

通过以上步骤,您可以快速搭建基于 pytest 的自动化测试体系。如需更复杂的插件(如生成 HTML 报告),可通过 pip install pytest-html 安装。

Tags:

最近发表
标签列表