python module_error ai_generated true

ModuleNotFoundError: 没有名为 'myapp' 的模块

ModuleNotFoundError: No module named 'myapp'

ID: python/pytest-import-mode-src-not-found

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-05-21首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

pytest 默认 import 模式(prepend)将测试目录插入 sys.path,而非项目根目录。src/ 布局的包在未安装或未配置路径时无法从 tests 导入。

English

pytest's default import mode (prepend) inserts test directories into sys.path, not the project root. A src/ layout package isn't importable from tests without installation or path configuration.

generic

解决方案

  1. 95% 成功率
    pip install -e .
    # or with pyproject.toml [build-system] set, uv pip install -e .
  2. 90% 成功率
    # pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ["src"]
    addopts = "--import-mode=importlib"

无效尝试

常见但无效的做法:

  1. 70% 失败

    Relative paths break depending on CWD; also pollutes sys.path and hides packaging issues.

  2. 60% 失败

    Works locally but isn't reproducible in CI; pytest may still use prepend mode and shadow the path.