python config_error ai_generated true

ERROR: 未找到收集器 导入测试模块 'tests/test_api.py' 时出现 ImportError。 提示:确保测试模块/包的 Python 名称有效。 ModuleNotFoundError: 没有名为 'myapp' 的模块

ERROR: found no collectors ImportError while importing test module 'tests/test_api.py'. Hint: make sure your test modules/packages have valid Python names. ModuleNotFoundError: No module named 'myapp'

ID: python/pytest-collection-import-mismatch-src-layout

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

版本兼容性

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

根因分析

项目使用 src/ 布局,包未安装(未执行 pip install -e .)且 pytest 的 rootdir 不包含 src/,导致包不在 sys.path 上。

English

The project uses a src/ layout and the package is not on sys.path because it has not been installed (pip install -e .) and pytest's rootdir does not include src/.

generic

解决方案

  1. 95% 成功率
    pip install -e .
    # or with pyproject.toml
    pip install -e '.[dev]'
    pytest -q
  2. 90% 成功率
    # pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ['src']
    testpaths = ['tests']

无效尝试

常见但无效的做法:

  1. 55% 失败

    Duplicates boilerplate across files, breaks when tests run from a different cwd, and hides packaging bugs.

  2. 50% 失败

    Not persisted for CI or other contributors; failures reappear in fresh environments.