以下是 pytest 常用命令参数 的整理,涵盖测试运行、过滤、调试、报告等常见场景,方便你高效使用 pytest:
1. 基本测试运行
命令 | 说明 |
---|
pytest | 运行当前目录及子目录下所有测试(test_*.py 或 *_test.py ) |
pytest path/to/test_file.py | 运行指定测试文件 |
pytest path/to/test_dir/ | 运行指定目录下的所有测试 |
pytest -v | 显示详细输出(每个测试用例的名称和结果) |
pytest -s | 输出调试信息,包括输出print信息 |
pytest -q | 静默模式(只显示简要结果) |
pytest -n | 多线程或分布式执行测试用例 |
2. 选择特定测试
命令 | 说明 |
---|
pytest -k "keyword" | 只运行名称包含 keyword 的测试(模糊匹配) 例:pytest -k "login" 匹配 test_login() 或 TestLogin |
pytest path/to/test_file.py::test_func | 运行指定文件的特定测试函数 |
pytest path/to/test_file.py::TestClass::test_method | 运行指定类的特定测试方法 |
pytest -m marker | 运行标记(mark)为 marker 的测试 需先在测试中用 @pytest.mark.marker 标记 |
3. 失败控制与调试
命令 | 说明 |
---|
pytest --lf 或 --last-failed | 只重新运行上次失败的测试 |
pytest --ff 或 --failed-first | 先运行上次失败的测试,再运行其他 |
pytest -x | 遇到第一个失败时停止测试 |
pytest --maxfail=2 | 最多允许 2 次失败,之后停止 |
pytest --pdb | 测试失败时自动进入 pdb 调试器 |
4. 测试报告与输出
命令 | 说明 |
---|
pytest -rA | 显示所有测试结果的详细摘要 |
pytest --durations=5 | 显示最慢的 5 个测试(性能分析) |
pytest --cov=path/to/module | 生成代码覆盖率报告(需安装 pytest-cov ) |
pytest --html=report.html | 生成 HTML 测试报告(需安装 pytest-html ) |
5. 参数化与 Fixture
命令 | 说明 |
---|
pytest --fixtures | 查看所有可用的 fixture |
pytest --setup-show | 显示测试的 fixture 执行顺序 |
6. 其他实用参数
命令 | 说明 |
---|
pytest --collect-only | 只列出所有测试用例,不执行 |
pytest --version | 查看 pytest 版本 |
pytest -h | 查看完整帮助文档 |
常用组合示例
- 快速重跑失败测试:
pytest --lf -v
- 只运行标记为
smoke
的测试:pytest -m smoke
- 调试慢测试:
pytest --durations=10 -v
- 生成覆盖率报告:
pytest --cov=src --cov-report=html
配置文件(pytest.ini
)
可以在项目根目录创建 pytest.ini
文件,默认配置常用参数,例如:
[pytest]
addopts = -v --html=report.html
markers =
smoke: 冒烟测试
slow: 慢测试