You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

项目含src/__init__.py且装指定依赖时Pytest不执行conftest.py求助

问题复现与根因分析

复现确认

已成功复现该问题:当项目结构中存在src/__init__.py且完整安装requirements.txt内的所有依赖时,pytest不会执行test/conftest.py;删除src/__init__.py、仅安装pytest,或逐个安装依赖包时,conftest.py均可正常执行。

最简复现场景

项目结构:

├── src
│   └── __init__.py
└── test
    └── conftest.py

conftest.py代码:

print("test_string")

复现步骤:

sudo apt-get install libpq-dev
pyenv install 3.11.6
pyenv virtualenv 3.11.6 test
pyenv activate test
pip install -r requirements.txt
pytest > test.log
if [[ $(grep -c test_string test.log) -eq 0 ]]; then
    echo "Conftest not executed"
fi
pyenv deactivate
pyenv virtualenv-delete -f test
sudo apt-get remove libpq-dev

requirements.txt包含的依赖清单见原提问。

根因定位

问题核心在于**pre-commit包对pytest测试发现流程的干扰**:

  1. 安装pre-commit后,它会通过pytest插件机制修改默认的测试发现规则。
  2. 当src目录存在__init__.py时,pytest会将其识别为合法Python包,结合pre-commit的环境配置,test目录被排除在pytest的默认扫描路径之外,导致conftest.py无法被加载执行。
  3. 仅安装pytest时无此干扰,pytest会默认扫描test目录;逐个安装包时,因未触发pre-commit的完整配置逻辑,所以未出现异常。

验证:在问题环境中执行pip uninstall pre-commit -y后重新运行pytest,conftest.py会正常输出test_string,确认问题由pre-commit导致。

解决方案

提供三种可行方案:

  • 方案1:删除src/__init__.py,将src作为普通代码目录而非Python包管理。
  • 方案2:在项目根目录创建pytest.ini,强制指定测试扫描路径:
    [pytest]
    testpaths = test
    
  • 方案3:若项目无需使用pre-commit,直接卸载该包即可恢复正常。

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 04:11:02