python type_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-06-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.11 active — — —
3.12 active — — —

Root Cause

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.

generic

中文

MagicMock 被返回,但期望的是异步上下文管理器或特定接口。MagicMock 会自动创建属性,但其返回值不可 await;协程应使用 AsyncMock 并配置魔术方法。

Workarounds

  1. 93% success
    Use AsyncMock for async interfaces:
      from unittest.mock import AsyncMock
      mock_client = AsyncMock()
      mock_client.get.return_value = {'ok': True}
  2. 85% success
    Configure magic methods on MagicMock:
      m = MagicMock()
      m.__aenter__ = AsyncMock(return_value=m)
      m.__aexit__ = AsyncMock(return_value=None)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Fixes only the first error; await-related TypeError persists for async usage.

  2. 85% fail

    Plain Mock does not support __aenter__/__aexit__ or magic methods; more AttributeErrors appear.