如何解决Bitbucket Pipeline中pytest-xdist并行跑pytest的报错
pytest-xdist在Bitbucket Pipeline报错解决方案
问题根因
核心报错为pluggy.manager.PluginValidationError: unknown hook 'pytest_warning_recorded',本质是pytest与pytest-xdist版本不匹配。
当前CI环境的版本组合:
- pytest 5.4.3
- pytest-xdist 2.2.1
pytest_warning_recorded是pytest 6.0才新增的钩子,pytest-xdist 2.x全系列要求pytest版本≥6.0。本地可正常运行是因为本地pytest版本符合要求,CI环境因依赖未锁定或缓存遗留问题安装了旧版pytest,导致worker进程注册钩子失败,后续的KeyError: <WorkerController gw0>是worker异常退出后的连锁反应。
可落地解决方案
- 方案1:升级pytest版本(推荐,当前Python 3.7.5可兼容pytest最高至7.2版本)
- 修改依赖配置文件(requirements.txt/pyproject.toml),指定pytest版本≥6.0,示例:
pytest>=6.0 - 同步调整配套插件版本:pytest-forked需≥1.4.0,pluggy版本≥0.13.0(当前CI的pluggy 0.13.1已符合要求)
- 清理CI的依赖缓存,重新安装锁定后的依赖,避免拉取旧缓存包
- 修改依赖配置文件(requirements.txt/pyproject.toml),指定pytest版本≥6.0,示例:
- 方案2:降级pytest-xdist版本(适用于无法升级pytest的场景)
- 将pytest-xdist版本锁定为兼容pytest 5.x的最后一个稳定版1.34.0,示例:
pytest-xdist==1.34.0 - 配套将pytest-forked版本固定为1.3.0(当前CI的pytest-forked版本已符合要求)
- 将pytest-xdist版本锁定为兼容pytest 5.x的最后一个稳定版1.34.0,示例:
- 通用优化:建议使用锁文件(如requirements.lock/poetry.lock)固定所有依赖版本,避免本地与CI环境出现依赖版本漂移
验证步骤
- 在CI测试步骤前新增依赖打印命令:
pip list | grep -E "pytest|xdist|pluggy|forked",确认CI安装的依赖版本与本地完全一致 - 临时取消并行参数,先执行单线程测试
coverage run -m pytest,确认基础测试无其他问题后,再开启并行执行
内容的提问来源于stack exchange,提问作者ModellingGeek
相关产品推荐
相关产品推荐

