python config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-02-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 55% fail

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

  2. 50% fail

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