python install_error ai_generated true

收集 tests/test_api.py 时出错 导入测试模块时 ImportError。 ModuleNotFoundError: 没有名为 'myapp' 的模块

ERROR collecting tests/test_api.py ImportError while importing test module 'tests/test_api.py'. ModuleNotFoundError: No module named 'myapp'

ID: python/pytest-collection-import-error

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

版本兼容性

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

根因分析

pytest 仅在特定模式下将 rootdir 加入 sys.path。当从子目录运行 'pytest tests/' 或使用 src 布局时,包根目录不在 sys.path 上。

English

pytest adds the rootdir to sys.path only in certain modes. When invoked as 'pytest tests/' from a subdirectory or with a src layout, the package root is not on sys.path.

generic

解决方案

  1. 95% 成功率
    pip install -e .
    # then run: pytest
  2. 90% 成功率
    # pytest.ini
    [pytest]
    pythonpath = src

无效尝试

常见但无效的做法:

  1. 60% 失败

    The CWD is not always the project root, and sys.path hacks break when tests run from CI with a different working directory.

  2. 50% 失败

    This works only if the CWD is the project root; under src layout it still fails because the package lives under src/.