python module_error ai_generated true

import file mismatch: /proj/tests/test_a.py has __pycache__ ... imported module 'test_a' has this __file__ attribute: /proj/tests/sub/test_a.py

ID: python/pytest-import-file-mismatch

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-01-22First Seen

Version Compatibility

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

Root Cause

Two test files share the same basename in different directories without __init__.py, so Python's module cache collides on the module name 'test_a'.

generic

中文

两个测试文件在不同目录下具有相同的基本名称,且没有 __init__.py,导致 Python 模块缓存在模块名 'test_a' 上发生冲突。

Workarounds

  1. 95% success
    touch tests/__init__.py tests/sub/__init__.py
    # then rerun: pytest -q
  2. 90% success
    # pytest.ini
    [pytest]
    addopts = --import-mode=importlib
  3. 85% success
    mv tests/test_a.py tests/test_alpha.py
    mv tests/sub/test_a.py tests/sub/test_a_sub.py

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Cache regeneration recreates the same collision on the next run.

  2. 95% fail

    Hash randomization is unrelated to module name resolution.

  3. 40% fail

    May work short-term but the same pattern recurs as the suite grows.