python / python/cpython

`mock.patch(..., autospec=True)` on a `functools.partialmethod` attribute produces a completely uncallable mock

未關閉
#153,581 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

stdlib type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

Autospeccing a class attribute that is a functools.partialmethod (either via mock.patch.object(cls, name, autospec=True) or mock.create_autospec(cls, ...) combined with a direct
mock.patch.object on that one attribute) produces a unittest.mock.NonCallableMagicMock. Calling it then raises TypeError: 'NonCallableMagicMock' object is not callable, even though the real attribute is perfectly callable (instance.method(...) works fine on the un-mocked class).

import functools
from unittest import mock

class Client:
    def _send_request(self, method, url):
        return method, url

    _send_post_request = functools.partialmethod(_send_request, "POST")

with mock.patch.object(Client, "_send_post_request", autospec=True) as m:
    print(type(m))  # <class 'unittest.mock.NonCallableMagicMock'>
    client = Client()
    client._send_post_request("https://example.com")
    # TypeError: 'NonCallableMagicMock' object is not callable
Root cause:

_patch.get_original() (Lib/unittest/mock.py) reads the attribute via target.__dict__[name] first, deliberately bypassing the descriptor protocol (this is needed to support patching descriptors like @property correctly). For a functools.partialmethod attribute, this yields the
raw partialmethod instance rather than the bound-callable object that getattr(instance, name) would produce.

functools.partialmethod objects are not themselves callable (they have no __call__; only __get__, since they are non-data descriptors meant to be resolved through attribute access):

>>> import functools, inspect
>>> p = functools.partialmethod(lambda self, a: None, 1)
>>> callable(p)
False
>>> inspect.signature(p)
Traceback (most recent call last):
  ...
TypeError: functools.partialmethod(<function <lambda> at 0x...>, 1, ) is not a callable object
CPython versions tested on:

3.12, but tested on main as well.

Operating systems tested on:

Linux

Linked PRs
  • gh-153582

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

該 issue 指出了 Lib/unittest/mock.py 和 _patch.get_original();首先執行 partialmethod 重現,並追蹤 autospec 如何處理原始描述器。完成標準是:使用 autospec patch 該屬性會產生一個可呼叫的 mock,且所示的用戶端呼叫不再引發 TypeError,同時為此情況加入回歸覆蓋。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
testing
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。