pytest-dev/pytest-mock

`self` is not passed with specced/autospecced PropertyMock

WilliamDEdwards opened this issue · 2 comments

When mocking a function, I can pass self with autospec=True:

def do_thing_side_effect(self):
  pass

mocker.patch('module.class.do_thing', side_effect=do_thing_side_effect, autospec=True)

When mocking a property getter, I am unable to pass self with either autospec=True or spec=True:

def thing_side_effect(self):
  pass

mocker.patch('module.class.thing', new=mocker.PropertyMock(side_effect=thing_side_effect, autospec=True))

This yields:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/unittest/mock.py", line 2848, in __get__
    return self()
  File "/usr/local/lib/python3.9/unittest/mock.py", line 1092, in __call__
    return self._mock_call(*args, **kwargs)
  File "/usr/local/lib/python3.9/unittest/mock.py", line 1096, in _mock_call
    return self._execute_mock_call(*args, **kwargs)
  File "/usr/local/lib/python3.9/unittest/mock.py", line 1157, in _execute_mock_call
    result = effect(*args, **kwargs)
TypeError: thing_side_effect() missing 1 required positional argument: 'self'

Using spec instead of autospec causes the same error:

from module import class

def thing_side_effect(self):
  pass

mocker.patch('module.class.thing', new=mocker.PropertyMock(side_effect=thing_side_effect, spec=class.thing))

Using spec + new_callable instead of new causes the same error:

from module import class

def thing_side_effect(self):
  pass

mocker.patch('module.class.thing', spec=mocker.create_autospec(class.thing, side_effect=thing_side_effect, new_callable=mocker.PropertyMock)

Hi,

Not sure how to accomplish that I'm afraid.

See if you can do the same using plain unittest.mock; if you can, then it is a bug in pytest-mock and we should investigate, if not, I suggest posting somewhere else using a unittest.mock-based example to see if others can help.

pytest-mock is a thin-wrapper around unittest.mock.

See if you can do the same using plain unittest.mock; if you can, then it is a bug in pytest-mock and we should investigate, if not, I suggest posting somewhere else using a unittest.mock-based example to see if others can help.

Created python/cpython#100291