`mock.patch(..., autospec=True)` on a `functools.partialmethod` attribute produces a completely uncallable mock
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 77.2k
- フォーク
- 35.9k
- 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
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- 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