python install_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 60% fail

    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% fail

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