python module_error ai_generated true

ModuleNotFoundError: No module named 'myapp' # when running pytest from repo root with src/ layout

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2025-06-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

src/ layout requires the package to be installed or on sys.path; running pytest from the repo root without `pip install -e .` leaves src/myapp unreachable.

generic

中文

src/ 布局要求包已安装或在 sys.path 上;未执行 `pip install -e .` 时从仓库根运行 pytest 无法访问 src/myapp。

Workarounds

  1. 98% success
    pip install -e .
    # or with build backend
    pip install -e ".[test]"
    
    # then
    pytest
  2. 92% success
    # pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ["src"]
    testpaths = ["tests"]

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Duplicated boilerplate and still fails for subprocess-based tests or coverage tools that re-import.

  2. 70% fail

    Abandons src/ layout benefits (isolation, editable install correctness) and may break packaging.

  3. 85% fail

    Not reproducible in CI; each developer must remember the env var.