Pytest 9.1.0
Pytest 9.1.0 已于 2026-06-13 发布,建议 Python 3.10+ 使用虚拟环境安装;9.x 系列最大的升级点是原生 TOML 配置和 strict 模式语义变化,升级老项目时配置和 CI 需要重点核查。
安装
# 推荐:先建虚拟环境
python -m venv .venv
source .venv/bin/activate # macOS/Linux
# .venv\Scripts\activate # Windows
# 安装指定版本
pip install pytest==9.1.0
# 验证
pytest --version常用插件:
pip install pytest-html pytest-cov pytest-xdist pytest-rerunfailures9.1.0 升级注意事项
| 变化点 | 影响 | 建议 |
|---|---|---|
--doctest-modules + autouse fixture | module/package/session 级 autouse fixture 可能执行两次 | 把这类 fixture 移到 conftest.py 里 |
strict = true | 一次性开启 strict_config / strict_markers / strict_parametrization_ids / strict_xfail | 开启前锁 minversion = "9.0" |
PytestRemovedIn9Warning | 9.0 默认 error,9.1 直接移除该类 | 9.1 下不能再靠 ignore 降级,需直接修用例 |
pytest a/ a/b | 重叠路径自动去重 | 需要旧行为加 --keep-duplicates |
| CI 判定 | $CI / $BUILD_NUMBER 必须是非空值 | CI="" 或 CI=0 不再视为 CI 模式 |
推荐项目结构
project/
├── src/
│ └── mypkg/
│ └── math_utils.py
├── tests/
│ ├── conftest.py
│ └── test_math_utils.py
├── pyproject.toml
└── requirements-dev.txt配置(推荐 pyproject.toml)
[tool.pytest.ini_options]
minversion = "9.0"
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = ["-ra", "-q", "--strict-markers"]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration",
]9.0 起 [tool.pytest] 和 [tool.pytest.ini_options] 不能同时存在,选一个即可。
编写测试
# tests/test_math_utils.py
from mypkg.math_utils import add, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_divide_by_zero():
import pytest
with pytest.raises(ZeroDivisionError):
divide(1, 0)常用运行方式
pytest # 运行全部用例
pytest -v # 详细输出
pytest -v -s # 详细输出 + 显示 print
pytest tests/test_math_utils.py::test_add # 指定用例
pytest -k "add" # 按名称筛选
pytest -m "not slow" # 按标记筛选
pytest -x # 首次失败即停
pytest --lf # 只跑上次失败的
pytest --html=report.html # 生成 HTML 报告
pytest -n auto # 并行执行
pytest --cov=src --cov-report=html # 覆盖率报告CI 中推荐写法
pip install -r requirements-dev.txt
pytest -ra --strict-markers --tb=short如果项目还在用 pytest.ini,建议迁移到 pyproject.toml 的 [tool.pytest.ini_options],避免 9.x 下出现多配置文件告警。