python module_error ai_generated true

ModuleNotFoundError:没有名为 'myapp' 的模块 文件 "/app/tests/test_api.py",第 3 行,在 <module> 中 from myapp.api import create_app

ModuleNotFoundError: No module named 'myapp' File "/app/tests/test_api.py", line 3, in <module> from myapp.api import create_app

ID: python/pytest-import-mode-sys-path

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

版本兼容性

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

根因分析

pytest 运行时项目根目录不在 sys.path 上。当从项目根目录以外的目录调用测试,或者包未安装(pip install -e .)且项目根目录没有 conftest.py 来锚定 rootdir 时,就会发生这种情况。

English

The project root is not on sys.path when pytest runs. This happens when tests are invoked from a directory other than the project root, or when the package is not installed (pip install -e .) and there is no conftest.py at the project root to anchor rootdir.

generic

解决方案

  1. 97% 成功率
    pip install -e .
    pytest tests/
  2. 90% 成功率
    # project/conftest.py (empty is enough)
    touch conftest.py
    pytest tests/
  3. 93% 成功率
    # pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ["."]

无效尝试

常见但无效的做法:

  1. 80% 失败

    Depends on CWD at runtime; breaks in CI when pytest is invoked from a different directory, and pollutes each test file.

  2. 75% 失败

    Works interactively but not in CI or IDE test runners; teammates hit the same error.