Banner

Pytest 9.1.0

2026-11-19

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-rerunfailures

9.1.0 升级注意事项

变化点影响建议
--doctest-modules + autouse fixturemodule/package/session 级 autouse fixture 可能执行两次把这类 fixture 移到 conftest.py 里
strict = true一次性开启 strict_config / strict_markers / strict_parametrization_ids / strict_xfail开启前锁 minversion = "9.0"
PytestRemovedIn9Warning9.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 下出现多配置文件告警。

14