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