什么是 pytest?
pytest 是一个功能强大且易于使用的 Python 测试框架,支持单元测试、集成测试等多种测试场景。其核心优势包括:
- 自动发现测试用例(无需手动编写测试类)
- 简洁的断言语法(如
assert 1 + 1 == 2
) - 内置支持参数化测试、fixtures 和插件系统
- 与主流开发工具(如 PyCharm、VSCode)无缝集成
快速上手
安装 pytest
pip install pytest
编写第一个测试用例
# test_example.py
def test_addition():
assert 1 + 1 == 2
运行测试
pytest test_example.py
核心特性
- 🧪 参数化测试:通过
@pytest.mark.parametrize
支持多组输入 - 📦 插件生态:支持 pytest-html、pytest-xdist 等扩展
- 🧠 Fixture 管理:通过
pytest.fixture
实现测试前置条件
最佳实践
- 使用 fixtures 管理资源:例如数据库连接或 API token
- 结合 CI/CD 工具:如 GitHub Actions 或 Jenkins 实现自动化测试
- 生成 HTML 报告:通过
pytest-html
插件可视化测试结果