python module_error ai_generated true

ERROR collecting tests/test_api.py 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-error-importerror

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

Version Compatibility

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

Root Cause

pytest is invoked from a directory where the project root is not on sys.path, and the package is not installed in editable mode; pytest's rootdir-based sys.path insertion does not cover the source layout.

generic

中文

pytest 从项目根目录不在 sys.path 上的目录运行,且包未以可编辑模式安装;pytest 基于 rootdir 的 sys.path 插入不覆盖源码布局。

Workarounds

  1. 97% success
    pip install -e .
    # or with pyproject:
    pip install -e '.[dev]'
    pytest
  2. 94% success
    # pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ["."]
    testpaths = ["tests"]

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Works locally but breaks in CI where cwd differs; also fails when tests are collected before the insert executes for other modules.

  2. 65% fail

    Does not persist across CI jobs or IDE runs; developers forget to export it and the error returns.