Object (... 和 mock. patch (之间有什么区别

我试图理解这两种模仿方法的方法之间的区别。有人能帮忙区分一下吗?对于本例,我使用 passlib 库。

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)
31092 次浏览

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.