Explain how to properly mock user-defined `__call__`
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 77.2k
- Forks
- 35.9k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem bereitgestellten MagicMock-Reproducer unter Python 3.12 oder 3.13 und untersuche anschließend unittest/mock.py im Bereich von NonCallableMock.assert_called_with sowie die dabei verwendete Signaturbehandlung für spec=A. Vergleiche das Verhalten einer Klasse, die call definiert, mit dem aktuellen Traceback. Als abgeschlossen gilt die Aufgabe, wenn das dokumentierte oder implementierte Verhalten dafür sorgt, dass die gezeigte Assertion erfolgreich ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- testing-qa
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100