python / python/cpython

Explain how to properly mock user-defined `__call__`

未關閉
#131,383 9 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

Reproduce

from unittest.mock import MagicMock

class A:
    def __init__(self, a):
        ...

    def __call__(self, b, c):
        ...

mocker = MagicMock(spec=A)
mocker(21, 42)
mocker.assert_called_once_with(21, 42)

Current Behavior

TypeError                                 Traceback (most recent call last)
TypeError: too many positional arguments

The above exception was the direct cause of the following exception:

AssertionError                            Traceback (most recent call last)
Cell In[6], line 10
      8 mocker = MagicMock(spec=A)
      9 mocker(21, 42)
---> 10 mocker.assert_called_once_with(21, 42)

File ~/.pyenv/versions/3.12.2/lib/python3.12/unittest/mock.py:956, in NonCallableMock.assert_called_once_with(self, *args, **kwargs)
    951     msg = ("Expected '%s' to be called once. Called %s times.%s"
    952            % (self._mock_name or 'mock',
    953               self.call_count,
    954               self._calls_repr()))
    955     raise AssertionError(msg)
--> 956 return self.assert_called_with(*args, **kwargs)

File ~/.pyenv/versions/3.12.2/lib/python3.12/unittest/mock.py:944, in NonCallableMock.assert_called_with(self, *args, **kwargs)
    942 if actual != expected:
    943     cause = expected if isinstance(expected, Exception) else None
--> 944     raise AssertionError(_error_message()) from cause

AssertionError: expected call not found.
Expected: mock(21, 42)
  Actual: mock(21, 42)

Expected behaviour

It succeeds

Investigation

When passing a class that implements the __call__ method as spec to a mock instance it takes the it takes the signature of the __init__ which if it is the intended behavior is quite confusing.

CPython versions tested on:

3.12, 3.13

Operating systems tested on:

macOS, Linux

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

先在 Python 3.12 或 3.13 上使用提供的 MagicMock 重現程式碼,然後檢查 unittest/mock.py 中 NonCallableMock.assert_called_with 附近的程式碼,以及與 spec=A 相關的簽章處理。將定義了 call 的類別行為與目前的 traceback 進行比較。當文件化或已實作的行為使所示 assertion 成功時,即視為完成。

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

評估

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

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

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