python
type_error
ai_generated
true
AttributeError: Mock 对象没有属性 'close' 处理上述异常时又出现另一个异常: TypeError: MagicMock 对象不能在 'await' 表达式中使用
AttributeError: Mock object has no attribute 'close' During handling of the above exception, another exception occurred: TypeError: object MagicMock can't be used in 'await' expression
ID: python/pytest-mock-magicmock-spec-missing
80%修复率
88%置信度
0证据数
2024-06-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
MagicMock 被返回,但期望的是异步上下文管理器或特定接口。MagicMock 会自动创建属性,但其返回值不可 await;协程应使用 AsyncMock 并配置魔术方法。
English
A MagicMock was returned where an async context manager or specific interface was expected. MagicMock auto-creates attributes but its return values are not awaitable; use AsyncMock for coroutines and configure magic methods.
解决方案
-
93% 成功率
Use AsyncMock for async interfaces: from unittest.mock import AsyncMock mock_client = AsyncMock() mock_client.get.return_value = {'ok': True} -
85% 成功率
Configure magic methods on MagicMock: m = MagicMock() m.__aenter__ = AsyncMock(return_value=m) m.__aexit__ = AsyncMock(return_value=None)
无效尝试
常见但无效的做法:
-
70% 失败
Fixes only the first error; await-related TypeError persists for async usage.
-
85% 失败
Plain Mock does not support __aenter__/__aexit__ or magic methods; more AttributeErrors appear.