python module_error ai_generated true

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

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

Version Compatibility

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

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 75% fail

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