python module_error ai_generated true

导入文件不匹配: /proj/tests/test_a.py 具有 __pycache__ ... 导入的模块 'test_a' 具有此 __file__ 属性: /proj/tests/sub/test_a.py

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

    Cache regeneration recreates the same collision on the next run.

  2. 95% 失败

    Hash randomization is unrelated to module name resolution.

  3. 40% 失败

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