I am trying to understand the difference between these two approaches of mocking a method. Could someone please help distinguish them? For this example, I use the passlib library.
from passlib.context import CryptContext from unittest import mock with mock.patch.object(CryptContext, 'verify', return_value=True) as foo1: mycc = CryptContext(schemes='bcrypt_sha256') mypass = mycc.encrypt('test') assert mycc.verify('tesssst', mypass) with mock.patch('passlib.context.CryptContext.verify', return_value=True) as foo2: mycc = CryptContext(schemes='bcrypt_sha256') mypass = mycc.encrypt('test') assert mycc.verify('tesssst', mypass)
You already discovered the difference; mock.patch()
takes a string which will be resolved to an object when applying the patch, mock.patch.object()
takes a direct reference.
This means that mock.patch()
doesn't require that you import the object before patching, while mock.patch.object()
does require that you import before patching.
The latter is then easier to use if you already have a reference to the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With