python module_error ai_generated true

ImportError: 导入文件不匹配: 'test_models.py' 从 /app/tests/unit/test_models.py 导入 'test_models.py' 从 /app/tests/integration/test_models.py 导入 提示: 确保测试模块/包具有有效的 Python 名称。

ImportError: import file mismatch: 'test_models.py' imported from /app/tests/unit/test_models.py 'test_models.py' imported from /app/tests/integration/test_models.py Hint: make sure your test modules/packages have valid Python names.

ID: python/pytest-import-mismatch-conftest

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

版本兼容性

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

根因分析

两个测试文件同名但位于不同目录且没有 __init__.py 文件,pytest 基于 rootdir 的模块导入发生冲突,导致第二次导入失败。

English

Two test files share the same basename but live in different directories without __init__.py files, so pytest's rootdir-based module import collides and the second import fails.

generic

解决方案

  1. 95% 成功率
    Add __init__.py to each test directory so pytest treats them as packages:
    
    touch tests/unit/__init__.py tests/integration/__init__.py
  2. 90% 成功率
    Or set import mode globally in pytest.ini:
    
    [pytest]
    addopts = --import-mode=importlib

无效尝试

常见但无效的做法:

  1. 70% 失败

    Removes real test coverage; the collision returns as soon as another same-named file is added.

  2. 75% 失败

    Fixes the single run but CI still uses the default mode and fails identically.