pytest安装教程
·
安装pytest
确保已安装Python环境(建议3.7+版本)。通过pip直接安装最新版pytest:
pip install -U pytest
验证安装是否成功:
pytest --version
创建项目结构
新建一个项目目录,建议按以下结构组织文件:
project/
├── src/ # 源代码目录(可选)
├── tests/ # 测试代码目录
│ ├── __init__.py # 标识为Python包
│ └── test_sample.py # 示例测试文件
└── pytest.ini # 配置文件(可选)
编写测试用例
在test_sample.py中编写简单测试:
def func(x):
return x + 1
def test_answer():
assert func(3) == 5 # 故意失败用例
运行测试
在项目根目录执行:
pytest
或指定具体测试文件:
pytest tests/test_sample.py
配置pytest(可选)
创建pytest.ini文件定制行为:
[pytest]
python_files = test_*.py
testpaths = tests
addopts = -v --color=yes
常用插件推荐
-
pytest-cov: 测试覆盖率
pip install pytest-cov pytest --cov=src -
pytest-xdist: 并行测试
pip install pytest-xdist pytest -n 4 -
pytest-html: 生成HTML报告
pip install pytest-html pytest --html=report.html
更多推荐

所有评论(0)