magicmock.txt 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. .. currentmodule:: mock
  2. .. _magic-methods:
  3. Mocking Magic Methods
  4. =====================
  5. .. currentmodule:: mock
  6. :class:`Mock` supports mocking `magic methods
  7. <http://www.ironpythoninaction.com/magic-methods.html>`_. This allows mock
  8. objects to replace containers or other objects that implement Python
  9. protocols.
  10. Because magic methods are looked up differently from normal methods [#]_, this
  11. support has been specially implemented. This means that only specific magic
  12. methods are supported. The supported list includes *almost* all of them. If
  13. there are any missing that you need please let us know!
  14. You mock magic methods by setting the method you are interested in to a function
  15. or a mock instance. If you are using a function then it *must* take ``self`` as
  16. the first argument [#]_.
  17. .. doctest::
  18. >>> def __str__(self):
  19. ... return 'fooble'
  20. ...
  21. >>> mock = Mock()
  22. >>> mock.__str__ = __str__
  23. >>> str(mock)
  24. 'fooble'
  25. >>> mock = Mock()
  26. >>> mock.__str__ = Mock()
  27. >>> mock.__str__.return_value = 'fooble'
  28. >>> str(mock)
  29. 'fooble'
  30. >>> mock = Mock()
  31. >>> mock.__iter__ = Mock(return_value=iter([]))
  32. >>> list(mock)
  33. []
  34. One use case for this is for mocking objects used as context managers in a
  35. `with` statement:
  36. .. doctest::
  37. >>> mock = Mock()
  38. >>> mock.__enter__ = Mock(return_value='foo')
  39. >>> mock.__exit__ = Mock(return_value=False)
  40. >>> with mock as m:
  41. ... assert m == 'foo'
  42. ...
  43. >>> mock.__enter__.assert_called_with()
  44. >>> mock.__exit__.assert_called_with(None, None, None)
  45. Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
  46. are recorded in :attr:`~Mock.mock_calls`.
  47. .. note::
  48. If you use the `spec` keyword argument to create a mock then attempting to
  49. set a magic method that isn't in the spec will raise an `AttributeError`.
  50. The full list of supported magic methods is:
  51. * ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
  52. * ``__dir__``, ``__format__`` and ``__subclasses__``
  53. * ``__floor__``, ``__trunc__`` and ``__ceil__``
  54. * Comparisons: ``__cmp__``, ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
  55. ``__eq__`` and ``__ne__``
  56. * Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
  57. ``__contains__``, ``__len__``, ``__iter__``, ``__getslice__``,
  58. ``__setslice__``, ``__reversed__`` and ``__missing__``
  59. * Context manager: ``__enter__`` and ``__exit__``
  60. * Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
  61. * The numeric methods (including right hand and in-place variants):
  62. ``__add__``, ``__sub__``, ``__mul__``, ``__div__``,
  63. ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
  64. ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
  65. * Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``,
  66. ``__index__`` and ``__coerce__``
  67. * Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
  68. * Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
  69. ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
  70. The following methods are supported in Python 2 but don't exist in Python 3:
  71. * ``__unicode__``, ``__long__``, ``__oct__``, ``__hex__`` and ``__nonzero__``
  72. * ``__truediv__`` and ``__rtruediv__``
  73. The following methods are supported in Python 3 but don't exist in Python 2:
  74. * ``__bool__`` and ``__next__``
  75. The following methods exist but are *not* supported as they are either in use by
  76. mock, can't be set dynamically, or can cause problems:
  77. * ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
  78. * ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
  79. Magic Mock
  80. ==========
  81. There are two `MagicMock` variants: `MagicMock` and `NonCallableMagicMock`.
  82. .. class:: MagicMock(*args, **kw)
  83. ``MagicMock`` is a subclass of :class:`Mock` with default implementations
  84. of most of the magic methods. You can use ``MagicMock`` without having to
  85. configure the magic methods yourself.
  86. The constructor parameters have the same meaning as for :class:`Mock`.
  87. If you use the `spec` or `spec_set` arguments then *only* magic methods
  88. that exist in the spec will be created.
  89. .. class:: NonCallableMagicMock(*args, **kw)
  90. A non-callable version of `MagicMock`.
  91. The constructor parameters have the same meaning as for
  92. :class:`MagicMock`, with the exception of `return_value` and
  93. `side_effect` which have no meaning on a non-callable mock.
  94. The magic methods are setup with `MagicMock` objects, so you can configure them
  95. and use them in the usual way:
  96. .. doctest::
  97. >>> mock = MagicMock()
  98. >>> mock[3] = 'fish'
  99. >>> mock.__setitem__.assert_called_with(3, 'fish')
  100. >>> mock.__getitem__.return_value = 'result'
  101. >>> mock[2]
  102. 'result'
  103. By default many of the protocol methods are required to return objects of a
  104. specific type. These methods are preconfigured with a default return value, so
  105. that they can be used without you having to do anything if you aren't interested
  106. in the return value. You can still *set* the return value manually if you want
  107. to change the default.
  108. Methods and their defaults:
  109. * ``__lt__``: NotImplemented
  110. * ``__gt__``: NotImplemented
  111. * ``__le__``: NotImplemented
  112. * ``__ge__``: NotImplemented
  113. * ``__int__`` : 1
  114. * ``__contains__`` : False
  115. * ``__len__`` : 1
  116. * ``__iter__`` : iter([])
  117. * ``__exit__`` : False
  118. * ``__complex__`` : 1j
  119. * ``__float__`` : 1.0
  120. * ``__bool__`` : True
  121. * ``__nonzero__`` : True
  122. * ``__oct__`` : '1'
  123. * ``__hex__`` : '0x1'
  124. * ``__long__`` : long(1)
  125. * ``__index__`` : 1
  126. * ``__hash__`` : default hash for the mock
  127. * ``__str__`` : default str for the mock
  128. * ``__unicode__`` : default unicode for the mock
  129. * ``__sizeof__``: default sizeof for the mock
  130. For example:
  131. .. doctest::
  132. >>> mock = MagicMock()
  133. >>> int(mock)
  134. 1
  135. >>> len(mock)
  136. 0
  137. >>> hex(mock)
  138. '0x1'
  139. >>> list(mock)
  140. []
  141. >>> object() in mock
  142. False
  143. The two equality method, `__eq__` and `__ne__`, are special (changed in
  144. 0.7.2). They do the default equality comparison on identity, using a side
  145. effect, unless you change their return value to return something else:
  146. .. doctest::
  147. >>> MagicMock() == 3
  148. False
  149. >>> MagicMock() != 3
  150. True
  151. >>> mock = MagicMock()
  152. >>> mock.__eq__.return_value = True
  153. >>> mock == 3
  154. True
  155. In `0.8` the `__iter__` also gained special handling implemented with a
  156. side effect. The return value of `MagicMock.__iter__` can be any iterable
  157. object and isn't required to be an iterator:
  158. .. doctest::
  159. >>> mock = MagicMock()
  160. >>> mock.__iter__.return_value = ['a', 'b', 'c']
  161. >>> list(mock)
  162. ['a', 'b', 'c']
  163. >>> list(mock)
  164. ['a', 'b', 'c']
  165. If the return value *is* an iterator, then iterating over it once will consume
  166. it and subsequent iterations will result in an empty list:
  167. .. doctest::
  168. >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
  169. >>> list(mock)
  170. ['a', 'b', 'c']
  171. >>> list(mock)
  172. []
  173. ``MagicMock`` has all of the supported magic methods configured except for some
  174. of the obscure and obsolete ones. You can still set these up if you want.
  175. Magic methods that are supported but not setup by default in ``MagicMock`` are:
  176. * ``__cmp__``
  177. * ``__getslice__`` and ``__setslice__``
  178. * ``__coerce__``
  179. * ``__subclasses__``
  180. * ``__dir__``
  181. * ``__format__``
  182. * ``__get__``, ``__set__`` and ``__delete__``
  183. * ``__reversed__`` and ``__missing__``
  184. * ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
  185. ``__getstate__`` and ``__setstate__``
  186. * ``__getformat__`` and ``__setformat__``
  187. ------------
  188. .. [#] Magic methods *should* be looked up on the class rather than the
  189. instance. Different versions of Python are inconsistent about applying this
  190. rule. The supported protocol methods should work with all supported versions
  191. of Python.
  192. .. [#] The function is basically hooked up to the class, but each ``Mock``
  193. instance is kept isolated from the others.