Closed GoogleCodeExporter closed 8 years ago
I duck punched in my local test with the following lines, maybe they would be
helpful in developing this feature full fledged:
def mock_getitem(self, key):
if key not in self._children:
wraps = None
if self._wraps is not None:
wraps = getattr(self._wraps, key)
self._children[key] = self._get_child_mock(parent=self, name=key, wraps=wraps)
return self._children[key]
mock.Mock.__getitem__ = mock_getitem
Original comment by dnathe...@gmail.com
on 14 Feb 2012 at 11:35
mock.Mock does not support the magic methods. However mock.MagicMock does:
>>> from mock import MagicMock
>>> m = MagicMock()
>>> m[1]
<MagicMock name='mock.__getitem__()' id='4300277840'>
The only difference from MagicMock and your example is that magic methods are
not currently integrated with the wraps functionality. Mainly because no-one
has asked for it. (wraps is not very widely used at all in fact.)
Original comment by fuzzyman
on 15 Feb 2012 at 12:14
Thanks, I didn't understand the difference between mock and MagicMock or where
to use one over the other.
Original comment by dnathe...@gmail.com
on 15 Feb 2012 at 12:20
Support for magic methods is precisely the difference. In general MagicMock is
more capable and its safe to use as the "default" mock (which is what 0.8 does
- patch creates a MagicMock by default) unless you need a mock object that
*doesn't* respond to magic methods.
If you want some magic methods but not others, one way is to use a spec:
>>> m = MagicMock(spec=dict)
>>> m[1]
<MagicMock name='mock.__getitem__()' id='4300353744'>
>>> int(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'MagicMock'
>>> m = MagicMock(spec=int)
>>> int(m)
1
>>> m[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'MagicMock' object does not support indexing
Original comment by fuzzyman
on 15 Feb 2012 at 12:28
Original issue reported on code.google.com by
dnathe...@gmail.com
on 14 Feb 2012 at 10:34