python 3.8 项目可安全升级至 pytest 8.4.x(推荐 8.4.1+),但须避开 8.4.0(因 math.ulp 缺失致 pytest.approx 崩溃);测试函数必须返回 none,否则被跳过;子包中 conftest.py fixture 不再自动向上继承,需显式导入或调整结构。

直接结论:Python 3.8 项目可以安全升级到 pytest 8.4.x,但必须避开 8.4.0 初始发布版(已知存在 pytest.approx 导入崩溃问题),且需确认测试函数不返回非 None 值。
为什么不能直接 pip install -U pytest
pytest 8.4.0(2025年9月首发)在 Python 3.8 环境下存在一个紧急缺陷:pytest.approx 模块会无条件导入,而该模块内部依赖了 Python 3.9+ 才引入的 math.ulp,导致运行时抛出 AttributeError: module 'math' has no attribute 'ulp'。这个问题在 8.4.1 及后续版本(如 8.4.2)中已被修复。
- ✅ 推荐命令:
pip install "pytest>=8.4.1"或pip install pytest==8.4.2 - ❌ 避免命令:
pip install pytest(可能拉取 8.4.0)或pip install -U pytest(若本地已有旧版,升级路径可能卡在 8.4.0) - 验证是否生效:
pytest --version输出应为pytest 8.4.2或更高,且运行含assert x == pytest.approx(y)的用例不崩溃
test_* 函数返回值不再是“可选”的
pytest 8.4 开始强制要求:所有测试函数必须显式返回 None(即不写 return,或写 return None)。若返回任意其他值(如 return True、return "ok"),pytest 会报错 PytestCollectionWarning: cannot collect test_... because it has a return value,并跳过该用例。
安全 Python 代码沙箱:在隔离的沙箱中执行任意 Python 代码,预装 requests、NumPy、pandas 库。返回 stdout、stderr。
- 常见踩坑点:从 unittest 迁移来的脚本、带调试 print 的临时函数、或误把 fixture 当测试函数命名(如
def setup_db():被 pytest 自动识别为测试) - 快速检查方式:在项目根目录执行
pytest --collect-only | grep "test_",观察是否有 warning 提示 - 修复建议:批量搜索
return [^N]和return[^n](注意空格),确保测试函数末尾无非 None 返回;非测试逻辑请改名(如def init_db():)或加@pytest.mark.skip
conftest.py 中的 fixture 不再自动跨包继承 scope
pytest 8.0+ 加强了 pytest.Package 和 pytest.Directory 的语义区分。如果你的项目结构里有嵌套子包(如 tests/api/v1/ 和 tests/ui/),且依赖 conftest.py 放在 tests/ 根目录来统一提供 scope="session" 的 fixture,升级后可能失效——因为子包现在被识别为独立 Package,默认只加载同级及子级 conftest.py,不再向上穿透查找。
- 现象:原本能用的
db_sessionfixture 在tests/api/v1/test_user.py中报fixture 'db_session' not found - 解决方法:在每个需要该 fixture 的子包目录下,添加空的
__init__.py(确保它是 package),并在其conftest.py中用from ..conftest import db_session显式导入;或改用autouse=True+scope="session"并确保 session 级 fixture 定义在最外层conftest.py中(pytest 8.4 对此兼容性更好) - 验证技巧:加
-vv参数运行pytest tests/api/v1/,观察 fixture 解析路径是否包含预期的conftest.py
真正麻烦的不是版本号本身,而是那些藏在 conftest.py 里的隐式依赖和测试函数末尾多出来的 return "done" ——它们不会在 CI 报错,但会让一半用例静默消失。升级前先跑一遍 pytest --collect-only,比盲目更新更省时间。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










