@@ -743,23 +743,19 @@ Mocking unbound methods
743743~~~~~~~~~~~~~~~~~~~~~~~
744744
745745Sometimes 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
755751If 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
757753it is replacing, but delegates to a mock under the hood. You still get your
758754mock auto-created in exactly the same way as before. What it means though, is
759755that 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
776772If we don't use ``autospec=True `` then the unbound method is patched out
777773with a Mock instance instead, and isn't called with ``self ``.
0 commit comments