Lines Matching refs:mock
1 :mod:`unittest.mock` --- getting started
5 .. currentmodule:: unittest.mock
17 from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel
45 Once our mock has been used (``real.method`` in this example) it has methods
54 Once the mock has been called its :attr:`~Mock.called` attribute is set to
95 >>> mock = Mock()
96 >>> real.closer(mock)
97 >>> mock.close.assert_called_with()
99 We don't have to do any work to provide the 'close' method on our mock.
108 A common use case is to mock out classes instantiated by your code under test.
109 When you patch a class, then that class is replaced with a mock. Instances
110 are created by *calling the class*. This means you access the "mock instance"
115 mock. The ``Foo`` instance is the result of calling the mock, so it is configured
116 by modifying the mock :attr:`~Mock.return_value`. ::
122 >>> with patch('module.Foo') as mock:
123 ... instance = mock.return_value
133 the mock and can be helpful when the mock appears in test failure messages. The
134 name is also propagated to attributes or methods of the mock:
136 >>> mock = MagicMock(name='foo')
137 >>> mock
139 >>> mock.method
148 to child attributes of the mock - and also to their children.
150 >>> mock = MagicMock()
151 >>> mock.method()
152 <MagicMock name='mock.method()' id='...'>
153 >>> mock.attribute.method(10, x=53)
154 <MagicMock name='mock.attribute.method()' id='...'>
155 >>> mock.mock_calls
167 >>> mock.mock_calls == expected
175 <Mock name='mock.factory().deliver()' id='...'>
183 Setting the return values on a mock object is trivially easy:
185 >>> mock = Mock()
186 >>> mock.return_value = 3
187 >>> mock()
190 Of course you can do the same for methods on the mock:
192 >>> mock = Mock()
193 >>> mock.method.return_value = 3
194 >>> mock.method()
199 >>> mock = Mock(return_value=3)
200 >>> mock()
203 If you need an attribute setting on your mock, just do it:
205 >>> mock = Mock()
206 >>> mock.x = 3
207 >>> mock.x
210 Sometimes you want to mock up a more complex situation, like for example
211 ``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
217 >>> mock = Mock()
218 >>> cursor = mock.connection.cursor.return_value
220 >>> mock.connection.cursor().execute("SELECT 1")
223 >>> mock.mock_calls
225 >>> mock.mock_calls == expected
236 exception class or instance then the exception will be raised when the mock
239 >>> mock = Mock(side_effect=Exception('Boom!'))
240 >>> mock()
250 ``side_effect`` as an iterable is where your mock is going to be called several
252 ``side_effect`` to an iterable every call to the mock returns the next value
255 >>> mock = MagicMock(side_effect=[4, 5, 6])
256 >>> mock()
258 >>> mock()
260 >>> mock()
265 depending on what the mock is called with, ``side_effect`` can be a function.
266 The function will be called with the same arguments as the mock. Whatever the
273 >>> mock = MagicMock(side_effect=side_effect)
274 >>> mock(1, 2)
276 >>> mock(2, 3)
283 Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock
288 >>> mock = MagicMock() # AsyncMock also works here
289 >>> mock.__aiter__.return_value = [1, 2, 3]
291 ... return [i async for i in mock]
300 Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock
327 provide a mock of this object that *also* provides ``some_method``. If later
331 :class:`Mock` allows you to provide an object as a specification for the mock,
333 mock that don't exist on your specification object will immediately raise an
338 >>> mock = Mock(spec=SomeClass)
339 >>> mock.old_method()
345 mock, regardless of whether some parameters were passed as positional or
350 >>> mock = Mock(spec=f)
351 >>> mock(1, 2, 3)
352 <Mock name='mock()' id='140161580456576'>
353 >>> mock.assert_called_with(a=1, b=2, c=3)
355 If you want this smarter matching to also work with method calls on the mock,
380 mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
408 >>> mock = MagicMock(return_value=sentinel.file_handle)
409 >>> with patch('builtins.open', mock):
412 >>> mock.assert_called_with('filename', 'r')
436 (or :func:`patch.object` with two arguments). The mock will be created for you and
461 above the mock for ``test_module.ClassName2`` is passed in first.
476 Where you use :func:`patch` to create a mock for you, you can get a reference to the
477 mock using the "as" form of the with statement:
508 Mocking chained calls is actually straightforward with mock once you
509 understand the :attr:`~Mock.return_value` attribute. When a mock is called for
514 object has been used by interrogating the ``return_value`` mock:
516 >>> mock = Mock()
517 >>> mock().foo(a=2, b=3)
518 <Mock name='mock().foo()' id='...'>
519 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
545 To do this we create a mock instance as our mock backend and create a mock
560 With these we monkey patch the "mock backend" in place and can make the real
579 In some tests I wanted to mock out a call to :meth:`datetime.date.today`
585 class with a mock, but passing through calls to the constructor to the real
589 mock out the ``date`` class in the module under test. The :attr:`side_effect`
590 attribute on the mock date class is then set to a lambda function that returns
591 a real date. When the mock date class is called a real date will be
627 mock this using a :class:`MagicMock`.
641 How would we mock this class, and in particular its "iter" method?
726 mock for this, because if you replace an unbound method with a mock it doesn't
730 patch out methods with a mock that having to create a real function becomes a
735 it is replacing, but delegates to a mock under the hood. You still get your
736 mock auto-created in exactly the same way as before. What it means though, is
758 Checking multiple calls with mock
761 mock has a nice API for making assertions about how your mock objects are used.
763 >>> mock = Mock()
764 >>> mock.foo_bar.return_value = None
765 >>> mock.foo_bar('baz', spam='eggs')
766 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
768 If your mock is only being called once you can use the
772 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
773 >>> mock.foo_bar()
774 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
780 the *most recent* call. If your mock is going to be called several times, and
784 >>> mock = Mock(return_value=None)
785 >>> mock(1, 2, 3)
786 >>> mock(4, 5, 6)
787 >>> mock()
788 >>> mock.call_args_list
796 >>> mock.call_args_list == expected
803 Another situation is rare, but can bite you, is when your mock is called with
806 longer make assertions about what the values were when the mock was called.
834 One possibility would be for mock to copy the arguments you pass in. This
839 functionality. If you provide a ``side_effect`` function for a mock then
840 ``side_effect`` will be called with the same args as the mock. This gives us an
842 example I'm using *another* mock to store the arguments so that I can use the
843 mock methods for doing the assertion. Again a helper function sets this up for
847 >>> from unittest.mock import Mock, patch, DEFAULT
848 >>> def copy_call_args(mock):
855 ... mock.side_effect = side_effect
867 ``copy_call_args`` is called with the mock that will be called. It returns a new
868 mock that we do the assertion on. The ``side_effect`` function makes a copy of
873 If your mock is only going to be used once there is an easier way of
880 >>> mock = Mock(side_effect=side_effect)
881 >>> mock({6})
882 >>> mock(set())
906 AssertionError: Expected call: mock({1})
907 Actual call: mock(set())
909 <CopyingMock name='mock.foo' id='...'>
939 method, ``create_patch``, puts the patch in place and returns the created mock
967 You may want to mock a dictionary, or other container object, recording all
988 >>> mock = MagicMock()
989 >>> mock.__getitem__.side_effect = getitem
990 >>> mock.__setitem__.side_effect = setitem
997 >>> mock = Mock()
998 >>> mock.__getitem__ = Mock(side_effect=getitem)
999 >>> mock.__setitem__ = Mock(side_effect=setitem)
1005 >>> mock = MagicMock(spec_set=dict)
1006 >>> mock.__getitem__.side_effect = getitem
1007 >>> mock.__setitem__.side_effect = setitem
1009 With these side effect functions in place, the ``mock`` will behave like a normal
1013 >>> mock['a']
1015 >>> mock['c']
1017 >>> mock['d']
1021 >>> mock['b'] = 'fish'
1022 >>> mock['d'] = 'eggs'
1023 >>> mock['b']
1025 >>> mock['d']
1029 mock methods and attributes:
1031 >>> mock.__getitem__.call_args_list
1033 >>> mock.__setitem__.call_args_list
1059 value mocks are of the same type as the mock they are accessed on. This ensures
1062 available on the attributes and return value mock of instances of your
1066 <MyMock name='mock.foo' id='...'>
1070 <MyMock name='mock.foo()' id='...'>
1075 <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
1084 onto the mock constructor:
1092 <MagicMock name='mock.foo' id='...'>
1106 a function. These are harder to mock because they aren't using an object from
1116 That aside there is a way to use ``mock`` to affect the results of an import.
1123 This means you can use :func:`patch.dict` to *temporarily* put a mock in place
1124 in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
1132 >>> mock = Mock()
1133 >>> with patch.dict('sys.modules', {'fooble': mock}):
1137 <Mock name='mock.blob()' id='...'>
1139 >>> mock.blob.assert_called_once_with()
1146 >>> mock = Mock()
1147 >>> with patch.dict('sys.modules', {'fooble': mock}):
1151 <Mock name='mock.blob.blip()' id='...'>
1152 >>> mock.blob.blip.assert_called_once_with()
1154 With slightly more work you can also mock package imports:
1156 >>> mock = Mock()
1157 >>> modules = {'package': mock, 'package.module': mock.module}
1162 <Mock name='mock.module.fooble()' id='...'>
1163 >>> mock.module.fooble.assert_called_once_with()
1170 your mock objects through the :attr:`~Mock.method_calls` attribute. This
1171 doesn't allow you to track the order of calls between separate mock objects,
1175 arbitrary attribute of a mock creates a child mock, we can create our separate
1176 mocks from a parent one. Calls to those child mock will then all be recorded,
1184 <Mock name='mock.foo.something()' id='...'>
1186 <Mock name='mock.bar.other.thing()' id='...'>
1192 the ``mock_calls`` attribute on the manager mock:
1199 them to a manager mock using the :meth:`~Mock.attach_mock` method. After
1209 <MagicMock name='mock.MockClass1().foo()' id='...'>
1210 <MagicMock name='mock.MockClass2().bar()' id='...'>
1225 <MagicMock name='mock().foo().bar().baz()' id='...'>
1227 <MagicMock name='mock.one().two().three()' id='...'>
1232 have been made to the mock, the assert still succeeds.
1234 Sometimes a mock may have several calls made to it, and you are only interested
1251 Suppose we expect some object to be passed to a mock that by default
1265 >>> mock = Mock(return_value=None)
1266 >>> mock(Foo(1, 2))
1267 >>> mock.assert_called_with(Foo(1, 2))
1299 >>> mock.assert_called_with(match_foo)
1303 method will be called, which compares the object the mock was called with
1308 >>> mock.assert_called_with(match_wrong)