网站首页 > 知识剖析 正文
一、pytest 简介
pytest 是 Python 中最流行的单元测试框架,相比内置的 unittest 更简洁高效,支持自动发现测试用例、参数化测试、异常验证及丰富的插件生态。其核心优势包括:
- 简洁语法:使用 assert 语句替代复杂的 TestCase 类
- 自动发现:自动识别 test_*.py 或 *_test.py 文件中的测试用例
- 扩展性强:支持 900+ 插件(如生成 HTML 报告、分布式测试等)
二、安装与验证
- 安装命令
pip install pytest # 基础安装
pip install pytest-html # 可选:生成 HTML 测试报告
- 验证安装:
pytest --version # 显示版本号即成功
- 测试文件命名规则
测试文件需以 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:每个模块执行前后运行
六、异常与标记
- 异常测试
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除零错误")
return a / b
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0) # 验证异常类型
- 测试标记
- 定义标记:在 pytest.ini 中配置
[pytest]
markers = smoke: 冒烟测试, serial: 串行执行
- 应用标记:
@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)支持
九、最佳实践
- 命名规范 测试函数名:test_<功能描述>_<场景> 测试类名:Test<功能模块>
- 独立性
每个测试用例应独立运行,避免共享状态。 - 分层设计
推荐分层结构:
tests/
├── conftest.py # 全局夹具
├── test_unit/ # 单元测试
└── test_integration/ # 集成测试
通过以上步骤,您可以快速搭建基于 pytest 的自动化测试体系。如需更复杂的插件(如生成 HTML 报告),可通过 pip install pytest-html 安装。
- 上一篇: web表单怎么测试?(表单测试思路)
- 下一篇: httprunner实战接口测试笔记,拿走不谢
猜你喜欢
- 2025-06-04 记一次实战给朋友站点测试(测试站点是什么意思)
- 2025-06-04 详细讲解性能测试(详细讲解性能测试题)
- 2025-06-04 [实战] cursor +claude-3.7+ go 实现批量网站敏感词检测
- 2025-06-04 Python最强大测试框架pytest(pytest框架原理)
- 2025-06-04 接口自动化的关键思路和解决方案,看完不会你捶我
- 2025-06-04 pytest测试框架pytest-cov插件生成代码覆盖率
- 2025-06-04 pytest单元测试框架(pytest框架设计)
- 2025-06-04 Pytest入门指南:轻松学会高效测试框架
- 2025-06-04 测试员进阶技能:如何有效地利用单元测试报告?
- 2025-06-04 测试开发必知必会:Pytest框架实战
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)