python
module_error
ai_generated
true
E ImportError: 无法从 'myapp' 导入名称 'app' (/path/to/myapp/__init__.py)
E ImportError: cannot import name 'app' from 'myapp' (/path/to/myapp/__init__.py)
ID: python/pytest-collection-error-import-mismatch
80%修复率
86%置信度
0证据数
2024-09-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
pytest无法收集测试,因为测试模块导入了目标模块中不存在的名称。这通常是由于循环导入、缺少 __init__.py 或包结构不正确造成的。
English
pytest fails to collect tests because a test module imports a name that doesn't exist in the target module. This often occurs due to circular imports, missing __init__.py, or incorrect package structure.
解决方案
-
95% 成功率
Check myapp/__init__.py and myapp/app.py: # myapp/__init__.py from .app import app Ensure the app object is defined in myapp/app.py.
-
90% 成功率
Run: pip install -e . Then in tests, use: from myapp import app
-
85% 成功率
In conftest.py: import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent))
无效尝试
常见但无效的做法:
-
90% 失败
This creates a dummy import that may hide the real issue and break other parts of the application.
-
95% 失败
This skips all tests, providing no validation and defeating the purpose of testing.
-
80% 失败
Relative imports only work within packages and may cause issues when running tests from different directories.