python module_error ai_generated true

ERROR 收集 tests/test_app.py 导入测试模块 '/app/tests/test_app.py' 时出现 ImportError。 提示:确保你的测试模块/包具有有效的 Python 名称。 回溯: conftest.py:5: in <module> from myapp import settings E ModuleNotFoundError: No module named 'myapp'

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

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-06-11首次发现

版本兼容性

版本状态引入弃用备注
6.x active — — —
7.x active — — —
8.x active — — —

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 75% 失败

    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% 失败

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