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

Poetry run pytest需tests目录有__init__.py才能运行的问题咨询

Poetry + pytest 模块导入问题的原因与解决办法

原因分析

  • poetry run pytest 直接调用pytest可执行文件时,Python解释器的sys.path默认不包含项目根目录(即app所在目录),因此无法找到app模块。
  • 进入poetry shell后执行python3 -m pytest tests/,通过-m参数启动pytest会自动将当前工作目录(项目根)加入sys.path,所以能正常导入app模块。
  • 给tests目录添加__init__.py后,pytest会自动将tests的父目录(项目根)添加到sys.path,这是pytest对传统包结构的兼容逻辑,但tests作为测试目录,本质上不需要__init__.py来成为Python包。

解决办法

  • 调整运行命令:用poetry run python -m pytest替代poetry run pytest,和shell里的运行逻辑保持一致,自动把项目根加入sys.path,无需修改目录结构。
  • 配置pytest的Python路径:在项目根目录的pyproject.toml中添加以下配置,强制pytest将项目根目录加入sys.path:
    [tool.pytest.ini_options]
    pythonpath = ["."]
    
    配置完成后,无论用poetry run pytest还是其他方式启动pytest,都能正常找到app模块,也不需要给tests目录加__init__.py。
  • 确认模块可编辑安装状态:执行poetry install(项目创建后通常已自动完成),将app模块以可编辑模式安装到Poetry虚拟环境中,让Python能全局识别该模块,不过前两种方法更直接适配测试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:10:51