mock.patch.object(...和mock.patch之间的区别是什么?

时间:2021-10-16 22:43:20

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.

我试图理解这两种模拟方法的方法之间的区别。有人可以帮助区分它们吗?对于此示例,我使用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)

1 个解决方案

#1


50  

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.

你已经发现了差异; mock.patch()接受一个字符串,在应用补丁时将解析为一个对象,mock.patch.object()接受直接引用。

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.

这意味着mock.patch()不需要在修补之前导入对象,而mock.patch.object()确实要求在修补之前导入。

The latter is then easier to use if you already have a reference to the object.

如果您已经有对象的引用,那么后者更容易使用。

#1


50  

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.

你已经发现了差异; mock.patch()接受一个字符串,在应用补丁时将解析为一个对象,mock.patch.object()接受直接引用。

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.

这意味着mock.patch()不需要在修补之前导入对象,而mock.patch.object()确实要求在修补之前导入。

The latter is then easier to use if you already have a reference to the object.

如果您已经有对象的引用,那么后者更容易使用。