模拟.patch.object(...和模拟.patch( [英] What is the difference between mock.patch.object(... and mock.patch(

查看:106
本文介绍了模拟.patch.object(...和模拟.patch(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解这两种模拟方法之间的区别.有人可以帮助区分他们吗?对于此示例,我使用passlib库.

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)

推荐答案

您已经发现了区别; mock.patch()采用一个字符串,当应用补丁时,该字符串将解析为对象 mock.patch.object()采用直接引用.

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.

如果您已经有对该对象的引用,则后者更易于使用.

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

这篇关于模拟.patch.object(...和模拟.patch(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆