目录
pytest 是 Python 生态中最流行、功能最强大的测试框架之一,它提供了简洁优雅的语法和丰富灵活的测试功能。下面我们将详细介绍 pytest 的核心概念和实用技巧。
1. 安装与基础配置
安装方法
使用 pip 安装最新版本 pytest:
pip install pytest
对于开发环境,建议同时安装常用插件:
pip install pytest pytest-cov pytest-xdist pytest-mock
版本检查
安装完成后可以检查版本:
pytest --version
配置文件
pytest 支持通过 pytest.ini
文件进行配置,例如:
[pytest]
addopts = -v --tb=short
python_files = test_*.py
python_classes = Test*
python_functions = test_*
2. 编写测试函数
基本结构
测试函数应遵循以下命名约定:
- 测试文件:
test_*.py
或*_test.py
- 测试函数:
test_*()
- 测试类:
Test*
示例测试文件 test_calculator.py
:
def add(a, b):
"""加法函数"""
return a + b
def test_add_integers():
"""测试整数加法"""
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_add_floats():
"""测试浮点数加法"""
assert add(0.1, 0.2) == pytest.approx(0.3)
断言机制
pytest 支持所有标准 Python 断言,并提供增强功能:
# 数值比较
assert result == expected
assert abs(result - expected) < 0.001
# 容器测试
assert item in collection
assert collection1 == collection2
# 异常测试
with pytest.raises(ValueError):
function_that_raises()
# 使用 pytest.approx 处理浮点数比较
assert 0.1 + 0.2 == pytest.approx(0.3)
3. 测试执行与报告
基本执行方式
# 运行所有测试
pytest
# 运行特定测试文件
pytest test_module.py
# 运行特定测试函数
pytest test_module.py::test_function
# 运行特定测试类
pytest test_module.py::TestClass
常用命令行选项
选项 | 说明 |
---|---|
-v |
详细输出 |
-x |
遇到第一个失败就停止 |
--maxfail=n |
允许最多 n 次失败 |
-k "expression" |
按名称筛选测试 |
--durations=n |