python module_error ai_generated true

导入文件不匹配: /app/tests/test_models.py 的 __file__ 属性为: /app/tests/test_models.py 与要收集的测试文件不同: /app/tests/unit/test_models.py 提示:删除 __pycache__ / .pyc 文件,和/或为测试文件模块使用唯一的基名

import file mismatch: /app/tests/test_models.py has this __file__ attribute: /app/tests/test_models.py which is not the same as the test file we want to collect: /app/tests/unit/test_models.py HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

ID: python/pytest-import-mismatch-missing-init

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

版本兼容性

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

根因分析

两个测试文件在不同目录下共享相同基名(test_models.py),但两个目录都不是 Python 包(缺少 __init__.py),因此 pytest 将两者都作为顶层模块 `test_models` 导入,导致冲突。

English

Two test files share the same basename (test_models.py) in different directories, but neither directory is a Python package (no __init__.py), so pytest imports both as top-level module `test_models`, causing a collision.

generic

解决方案

  1. 95% 成功率
    touch tests/__init__.py tests/unit/__init__.py
    # pytest then imports as tests.test_models and tests.unit.test_models
  2. 90% 成功率
    mv tests/test_models.py tests/test_api_models.py
    mv tests/unit/test_models.py tests/unit/test_db_models.py
  3. 85% 成功率
    # pytest.ini
    [pytest]
    addopts = --import-mode=importlib

无效尝试

常见但无效的做法:

  1. 85% 失败

    Clearing caches removes stale bytecode but does not fix the underlying module-name collision; the error reappears on the next run.

  2. 90% 失败

    Changing PYTHONPATH does not give the two files distinct module names; the collision is due to identical basenames without package context.