Skip to content

Commit e5e25df

Browse files
committed
bpo-32092: Updates docs referring to patching unbound methods
Signed-off-by: Claudiu Belu <cbelu@cloudbasesolutions.com>
1 parent 3f8c8ff commit e5e25df

1 file changed

Lines changed: 8 additions & 12 deletions

File tree

Doc/library/unittest.mock-examples.rst

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -743,23 +743,19 @@ Mocking unbound methods
743743
~~~~~~~~~~~~~~~~~~~~~~~
744744

745745
Sometimes a test needs to patch an *unbound method*, which means patching the
746-
method on the class rather than on the instance. In order to make assertions
747-
about which objects were calling this particular method, you need to pass
748-
``self`` as the first argument. The issue is that you can't patch with a mock for
749-
this, because if you replace an unbound method with a mock it doesn't become
750-
a bound method when fetched from the instance, and so it doesn't get ``self``
751-
passed in. The workaround is to patch the unbound method with a real function
752-
instead. The :func:`patch` decorator makes it so simple to patch out methods
753-
with a mock that having to create a real function becomes a nuisance.
746+
method on the class rather than on the instance. If you replace an unbound
747+
method with a plain mock, it doesn't become a bound method when fetched from
748+
an instance, so it never gets ``self`` passed in, and you also lose any
749+
checking of the arguments against the original method's signature.
754750

755751
If you pass ``autospec=True`` to patch then it does the patching with a
756752
*real* function object. This function object has the same signature as the one
757753
it is replacing, but delegates to a mock under the hood. You still get your
758754
mock auto-created in exactly the same way as before. What it means though, is
759755
that if you use it to patch out an unbound method on a class the mocked
760-
function will be turned into a bound method if it is fetched from an instance.
761-
It will have ``self`` passed in as the first argument, which is exactly what
762-
was needed:
756+
function will be turned into a bound method if it is fetched from an instance,
757+
just like the method it replaces. ``self`` is consumed automatically, so you
758+
don't need to account for it in call assertions:
763759

764760
>>> class Foo:
765761
... def foo(self):
@@ -771,7 +767,7 @@ was needed:
771767
... foo.foo()
772768
...
773769
'foo'
774-
>>> mock_foo.assert_called_once_with(foo)
770+
>>> mock_foo.assert_called_once_with()
775771

776772
If we don't use ``autospec=True`` then the unbound method is patched out
777773
with a Mock instance instead, and isn't called with ``self``.

0 commit comments

Comments
 (0)