python module_error ai_generated true

ERROR collecting tests/test_app.py ImportError while importing test module '/app/tests/test_app.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: conftest.py:5: in <module> from myapp import settings E ModuleNotFoundError: No module named 'myapp'

ID: python/pytest-collection-error-conftest-syntax

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

Version Compatibility

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

Root Cause

The project root is not on sys.path when pytest runs, so imports in conftest.py or test modules fail. This commonly happens when running pytest from a subdirectory or without installing the package in editable mode.

generic

中文

运行 pytest 时项目根目录不在 sys.path 上,导致 conftest.py 或测试模块中的导入失败。这通常发生在从子目录运行 pytest,或未以可编辑模式安装包时。

Workarounds

  1. 95% success
    pip install -e .
    # or with pyproject.toml:
    pip install -e '.[test]'
  2. 90% success
    # pytest.ini or pyproject.toml
    [tool.pytest.ini_options]
    pythonpath = ['.']
    # or CLI: pytest --import-mode=importlib

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Relative paths depend on CWD; running pytest from a different directory breaks it, and conftest.py is imported before test files so the fix is too late.

  2. 55% fail

    Works for interactive runs but is not persisted for CI or IDE test runners, leading to flaky 'works on my machine' behavior.